home *** CD-ROM | disk | FTP | other *** search
/ L' Effet Pommier 3 / L'Effet Pommier - Volume 03.iso / Programmation / Alpha ƒ / Help / Perl Commands < prev    next >
Text File  |  1995-12-28  |  231KB  |  5,316 lines

  1.  
  2. NAME
  3.      perl - Practical Extraction and Report Language
  4.  
  5. SYNOPSIS
  6.      perl [options] filename args
  7.  
  8. DESCRIPTION
  9.      Perl is an interpreted language optimized for scanning arbi-
  10.      trary  text  files,  extracting  information from those text
  11.      files, and printing reports based on that information.  It's
  12.      also  a good language for many system management tasks.  The
  13.      language is intended to be practical  (easy  to  use,  effi-
  14.      cient,  complete)  rather  than  beautiful  (tiny,  elegant,
  15.      minimal).  It combines (in  the  author's  opinion,  anyway)
  16.      some  of the best features of C, sed, awk, and sh, so people
  17.      familiar with those languages should have little  difficulty
  18.      with  it.  (Language historians will also note some vestiges
  19.      of csh, Pascal,  and  even  BASIC-PLUS.)  Expression  syntax
  20.      corresponds  quite  closely  to C expression syntax.  Unlike
  21.      most Unix utilities, perl does  not  arbitrarily  limit  the
  22.      size  of your data--if you've got the memory, perl can slurp
  23.      in your whole file as a  single  string.   Recursion  is  of
  24.      unlimited  depth.   And  the hash tables used by associative
  25.      arrays grow as necessary to  prevent  degraded  performance.
  26.      Perl  uses sophisticated pattern matching techniques to scan
  27.      large amounts of data very quickly.  Although optimized  for
  28.      scanning  text, perl can also deal with binary data, and can
  29.      make dbm files look like associative arrays  (where  dbm  is
  30.      available).   Setuid  perl scripts are safer than C programs
  31.      through a dataflow tracing  mechanism  which  prevents  many
  32.      stupid  security  holes.   If  you have a problem that would
  33.      ordinarily use sed or awk or sh, but it exceeds their  capa-
  34.      bilities  or must run a little faster, and you don't want to
  35.      write the silly thing in C, then perl may be for you.  There
  36.      are  also  translators to turn your sed and awk scripts into
  37.      perl scripts.  OK, enough hype.
  38.  
  39.      Upon startup, perl looks for your script in one of the  fol-
  40.      lowing places:
  41.  
  42.      1.  Specified line by line via -e switches  on  the  command
  43.          line.
  44.  
  45.      2.  Contained in the file specified by the first filename on
  46.          the  command line.  (Note that systems supporting the #!
  47.          notation invoke interpreters this way.)
  48.  
  49.      3.  Passed in implicitly  via  standard  input.   This  only
  50.          works  if there are no filename arguments--to pass argu-
  51.          ments to a stdin script you must explicitly specify a  -
  52.          for the script name.
  53.  
  54.      After locating your script, perl compiles it to an  internal
  55.      form.   If  the  script is syntactically correct, it is exe-
  56.      cuted.
  57.  
  58.      Options
  59.  
  60.      Note: on first reading this section may not make much  sense
  61.      to you.  It's here at the front for easy reference.
  62.  
  63.      A single-character option may be combined with the following
  64.      option, if any.  This is particularly useful when invoking a
  65.      script using the #! construct which only  allows  one  argu-
  66.      ment.  Example:
  67.  
  68.           #!/usr/bin/perl -spi.bak # same as -s -p -i.bak
  69.           ...
  70.  
  71.      Options include:
  72.  
  73.      -0digits
  74.           specifies the record separator ($/) as an octal number.
  75.           If  there  are  no  digits,  the  null character is the
  76.           separator.  Other switches may precede  or  follow  the
  77.           digits.   For  example,  if  you have a version of find
  78.           which can print filenames terminated by the null  char-
  79.           acter, you can say this:
  80.  
  81.               find . -name '*.bak' -print0 | perl -n0e unlink
  82.  
  83.           The special value 00 will cause Perl to slurp files  in
  84.           paragraph  mode.   The  value  0777  will cause Perl to
  85.           slurp files whole since there  is  no  legal  character
  86.           with that value.
  87.  
  88.      -a   turns on autosplit mode when used with a -n or -p.   An
  89.           implicit  split  command to the @F array is done as the
  90.           first thing inside the implicit while loop produced  by
  91.           the -n or -p.
  92.  
  93.                perl -ane 'print pop(@F), "\n";'
  94.  
  95.           is equivalent to
  96.  
  97.                while (<>) {
  98.                     @F = split(' ');
  99.                     print pop(@F), "\n";
  100.                }
  101.  
  102.      -c   causes perl to check the syntax of the script and  then
  103.           exit without executing it.
  104.  
  105.      -d   runs the script under the perl debugger.  See the  sec-
  106.           tion on Debugging.
  107.  
  108.      -Dnumber
  109.           sets debugging flags.  To watch how  it  executes  your
  110.           script,  use  -D14.   (This  only works if debugging is
  111.           compiled into your perl.) Another nice value is -D1024,
  112.           which  lists  your  compiled  syntax  tree.   And -D512
  113.           displays compiled regular expressions.
  114.  
  115.      -e commandline
  116.           may be used to enter one line of script.   Multiple  -e
  117.           commands  may be given to build up a multi-line script.
  118.           If -e is  given,  perl  will  not  look  for  a  script
  119.           filename in the argument list.
  120.  
  121.      -iextension
  122.           specifies that files processed by the <> construct  are
  123.           to  be  edited  in-place.  It does this by renaming the
  124.           input file, opening the output file by the  same  name,
  125.           and selecting that output file as the default for print
  126.           statements.  The extension, if supplied,  is  added  to
  127.           the  name of the old file to make a backup copy.  If no
  128.           extension is supplied, no backup is made.  Saying "perl
  129.           -p  -i.bak  -e "s/foo/bar/;" ... " is the same as using
  130.           the script:
  131.  
  132.                #!/usr/bin/perl -pi.bak
  133.                s/foo/bar/;
  134.  
  135.           which is equivalent to
  136.  
  137.                #!/usr/bin/perl
  138.                while (<>) {
  139.                     if ($ARGV ne $oldargv) {
  140.                          rename($ARGV, $ARGV . '.bak');
  141.                          open(ARGVOUT, ">$ARGV");
  142.                          select(ARGVOUT);
  143.                          $oldargv = $ARGV;
  144.                     }
  145.                     s/foo/bar/;
  146.                }
  147.                continue {
  148.                    print;     # this prints to original filename
  149.                }
  150.                select(STDOUT);
  151.  
  152.           except that the -i form doesn't need to  compare  $ARGV
  153.           to  $oldargv to know when the filename has changed.  It
  154.           does, however, use ARGVOUT for the selected filehandle.
  155.           Note  that  STDOUT  is  restored  as the default output
  156.           filehandle after the loop.
  157.  
  158.           You can use eof to locate the end of each  input  file,
  159.           in  case you want to append to each file, or reset line
  160.           numbering (see example under eof).
  161.  
  162.      -Idirectory
  163.           may be used in  conjunction  with  -P  to  tell  the  C
  164.           preprocessor  where  to  look  for  include  files.  By
  165.           default /usr/include and /usr/lib/perl are searched.
  166.  
  167.      -loctnum
  168.           enables automatic line-ending processing.  It  has  two
  169.           effects:  first, it automatically chops the line termi-
  170.           nator when used with -n or -p , and second, it  assigns
  171.           $\ to have the value of octnum so that any print state-
  172.           ments will have that line terminator added back on.  If
  173.           octnum  is omitted, sets $\ to the current value of $/.
  174.           For instance, to trim lines to 80 columns:
  175.  
  176.                perl -lpe 'substr($_, 80) = ""'
  177.  
  178.           Note that the assignment $\  =  $/  is  done  when  the
  179.           switch  is processed, so the input record separator can
  180.           be different than the output record separator if the -l
  181.           switch is followed by a -0 switch:
  182.  
  183.                gnufind / -print0 | perl -ln0e 'print "found $_" if -p'
  184.  
  185.           This sets $\ to newline and then sets $/  to  the  null
  186.           character.
  187.  
  188.      -n   causes perl to assume the following  loop  around  your
  189.           script,  which makes it iterate over filename arguments
  190.           somewhat like "sed -n" or awk:
  191.  
  192.                while (<>) {
  193.                     ...       # your script goes here
  194.                }
  195.  
  196.           Note that the lines are not printed by default.  See -p
  197.           to  have  lines  printed.   Here is an efficient way to
  198.           delete all files older than a week:
  199.  
  200.                find . -mtime +7 -print | perl -nle 'unlink;'
  201.  
  202.           This is faster than using  the  -exec  switch  of  find
  203.           because  you  don't  have  to  start a process on every
  204.           filename found.
  205.  
  206.      -p   causes perl to assume the following  loop  around  your
  207.           script,  which makes it iterate over filename arguments
  208.           somewhat like sed:
  209.  
  210.                while (<>) {
  211.                     ...       # your script goes here
  212.                } continue {
  213.                     print;
  214.                }
  215.  
  216.           Note that the  lines  are  printed  automatically.   To
  217.           suppress  printing use the -n switch.  A -p overrides a
  218.           -n switch.
  219.  
  220.      -P   causes your script to be run through the C preprocessor
  221.           before  compilation  by perl.  (Since both comments and
  222.           cpp directives begin with the # character,  you  should
  223.           avoid  starting  comments  with any words recognized by
  224.           the C preprocessor such as "if", "else" or "define".)
  225.  
  226.      -s   enables some rudimentary switch parsing for switches on
  227.           the  command  line after the script name but before any
  228.           filename arguments (or before a --).  Any switch  found
  229.           there  is removed from @ARGV and sets the corresponding
  230.           variable in the  perl  script.   The  following  script
  231.           prints "true" if and only if the script is invoked with
  232.           a -xyz switch.
  233.  
  234.                #!/usr/bin/perl -s
  235.                if ($xyz) { print "true\n"; }
  236.  
  237.      -S   makes perl use the PATH environment variable to  search
  238.           for  the  script  (unless the name of the script starts
  239.           with a slash).  Typically this is used  to  emulate  #!
  240.           startup  on machines that don't support #!, in the fol-
  241.           lowing manner:
  242.  
  243.                #!/usr/bin/perl
  244.                eval "exec /usr/bin/perl -S $0 $*"
  245.                     if $running_under_some_shell;
  246.  
  247.           The system ignores the first line and feeds the  script
  248.           to  /bin/sh,  which proceeds to try to execute the perl
  249.           script as a  shell  script.   The  shell  executes  the
  250.           second  line as a normal shell command, and thus starts
  251.           up the perl interpreter.  On some  systems  $0  doesn't
  252.           always  contain the full pathname, so the -S tells perl
  253.           to search for the  script  if  necessary.   After  perl
  254.           locates  the  script,  it  parses the lines and ignores
  255.           them because the variable $running_under_some_shell  is
  256.           never  true.   A  better  construct  than  $*  would be
  257.           ${1+"$@"}, which handles embedded spaces  and  such  in
  258.           the  filenames, but doesn't work if the script is being
  259.           interpreted by csh.  In order to  start  up  sh  rather
  260.           than  csh, some systems may have to replace the #! line
  261.           with a line containing just a colon, which will be pol-
  262.           itely  ignored  by  perl.   Other systems can't control
  263.           that, and need a totally devious  construct  that  will
  264.           work  under any of csh, sh or perl, such as the follow-
  265.           ing:
  266.  
  267.                eval '(exit $?0)' && eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
  268.                & eval 'exec /usr/bin/perl -S $0 $argv:q'
  269.                     if 0;
  270.  
  271.      -u   causes perl to dump core after compiling  your  script.
  272.           You  can  then  take this core dump and turn it into an
  273.           executable file by using the undump program  (not  sup-
  274.           plied).   This  speeds  startup  at the expense of some
  275.           disk space (which you can  minimize  by  stripping  the
  276.           executable).   (Still, a "hello world" executable comes
  277.           out to about 200K on my machine.) If you are  going  to
  278.           run your executable as a set-id program then you should
  279.           probably compile it using taintperl rather than  normal
  280.           perl.   If you want to execute a portion of your script
  281.           before dumping, use the dump operator  instead.   Note:
  282.           availability of undump is platform specific and may not
  283.           be available for a specific port of perl.
  284.  
  285.      -U   allows perl to do  unsafe  operations.   Currently  the
  286.           only  "unsafe"  operations  are the unlinking of direc-
  287.           tories while running as superuser, and  running  setuid
  288.           programs with fatal taint checks turned into warnings.
  289.  
  290.      -v   prints the version and patchlevel of your perl  execut-
  291.           able.
  292.  
  293.      -w   prints warnings about identifiers  that  are  mentioned
  294.           only  once,  and  scalar variables that are used before
  295.           being set.  Also warns about redefined subroutines, and
  296.           references  to  undefined  filehandles  or  filehandles
  297.           opened readonly that you are attempting  to  write  on.
  298.           Also  warns you if you use == on values that don't look
  299.           like numbers, and if your subroutines recurse more than
  300.           100 deep.
  301.  
  302.      -xdirectory
  303.           tells perl that the script is embedded  in  a  message.
  304.           Leading  garbage will be discarded until the first line
  305.           that starts with #! and  contains  the  string  "perl".
  306.           Any  meaningful  switches  on that line will be applied
  307.           (but only one group of switches, as with normal #! pro-
  308.           cessing).   If a directory name is specified, Perl will
  309.           switch to that directory  before  running  the  script.
  310.           The -x switch only controls the the disposal of leading
  311.           garbage.  The script must be terminated with __END__ if
  312.           there is trailing garbage to be ignored (the script can
  313.           process any or all of the trailing garbage via the DATA
  314.           filehandle if desired).
  315.  
  316.      Data Types and Objects
  317.  
  318.      Perl has three data types: scalars, arrays of  scalars,  and
  319.      associative arrays of scalars.  Normal arrays are indexed by
  320.      number, and associative arrays by string.
  321.  
  322.      The interpretation of operations and values  in  perl  some-
  323.      times  depends on the requirements of the context around the
  324.      operation or value.  There are three major contexts: string,
  325.      numeric  and  array.  Certain operations return array values
  326.      in contexts wanting an array, and scalar  values  otherwise.
  327.      (If this is true of an operation it will be mentioned in the
  328.      documentation for that operation.) Operations  which  return
  329.      scalars  don't  care  whether  the  context is looking for a
  330.      string or a number, but  scalar  variables  and  values  are
  331.      interpreted as strings or numbers as appropriate to the con-
  332.      text.  A scalar is interpreted as TRUE in the boolean  sense
  333.      if  it  is  not  the null string or 0.  Booleans returned by
  334.      operators are 1 for true and 0 or '' (the null  string)  for
  335.      false.
  336.  
  337.      There are actually two varieties of null string: defined and
  338.      undefined.   Undefined  null strings are returned when there
  339.      is no real value for something, such as when  there  was  an
  340.      error, or at end of file, or when you refer to an uninitial-
  341.      ized variable or element of an  array.   An  undefined  null
  342.      string  may become defined the first time you access it, but
  343.      prior to that you can use the defined() operator  to  deter-
  344.      mine whether the value is defined or not.
  345.  
  346.      References to scalar variables always begin with  '$',  even
  347.      when referring to a scalar that is part of an array.  Thus:
  348.  
  349.          $days           # a simple scalar variable
  350.          $days[28]       # 29th element of array @days
  351.          $days{'Feb'}    # one value from an associative array
  352.          $#days          # last index of array @days
  353.  
  354.      but entire arrays or array slices are denoted by '@':
  355.  
  356.          @days           # ($days[0], $days[1],... $days[n])
  357.          @days[3,4,5]    # same as @days[3..5]
  358.          @days{'a','c'}  # same as ($days{'a'},$days{'c'})
  359.  
  360.      and entire associative arrays are denoted by '%':
  361.  
  362.          %days           # (key1, val1, key2, val2 ...)
  363.  
  364.      Any of these eight constructs may serve as an  lvalue,  that
  365.      is,  may be assigned to.  (It also turns out that an assign-
  366.      ment is itself an lvalue in certain  contexts--see  examples
  367.      under  s, tr and chop.) Assignment to a scalar evaluates the
  368.      righthand side in a scalar context, while assignment  to  an
  369.      array  or  array  slice  evaluates  the righthand side in an
  370.      array context.
  371.  
  372.      You may  find  the  length  of  array  @days  by  evaluating
  373.      "$#days",  as in csh.  (Actually, it's not the length of the
  374.      array, it's the subscript of the last element,  since  there
  375.      is  (ordinarily) a 0th element.) Assigning to $#days changes
  376.      the length of the array.  Shortening an array by this method
  377.      does  not actually destroy any values.  Lengthening an array
  378.      that was previously shortened recovers the values that  were
  379.      in  those elements.  You can also gain some measure of effi-
  380.      ciency by preextending an array that is going  to  get  big.
  381.      (You  can  also  extend  an array by assigning to an element
  382.      that is off the end of the array.  This differs from assign-
  383.      ing to $#whatever in that intervening values are set to null
  384.      rather than recovered.) You can truncate an  array  down  to
  385.      nothing  by assigning the null list () to it.  The following
  386.      are exactly equivalent
  387.  
  388.           @whatever = ();
  389.           $#whatever = $[ - 1;
  390.  
  391.      If you evaluate an array in a scalar context, it returns the
  392.      length of the array.  The following is always true:
  393.  
  394.           scalar(@whatever) == $#whatever - $[ + 1;
  395.  
  396.      If you evaluate an associative array in a scalar context, it
  397.      returns  a value which is true if and only if the array con-
  398.      tains any elements.  (If there are any elements,  the  value
  399.      returned  is a string consisting of the number of used buck-
  400.      ets and the number of  allocated  buckets,  separated  by  a
  401.      slash.)
  402.  
  403.      Multi-dimensional arrays are not directly supported, but see
  404.      the  discussion of the $; variable later for a means of emu-
  405.      lating multiple subscripts with an associative  array.   You
  406.      could  also  write  a subroutine to turn multiple subscripts
  407.      into a single subscript.
  408.  
  409.      Every data type has its own  namespace.   You  can,  without
  410.      fear  of  conflict, use the same name for a scalar variable,
  411.      an array, an associative array, a filehandle,  a  subroutine
  412.      name,  and/or  a label.  Since variable and array references
  413.      always start with '$', '@', or  '%',  the  "reserved"  words
  414.      aren't  in  fact  reserved  with  respect to variable names.
  415.  
  416.      (They ARE reserved with respect to labels  and  filehandles,
  417.      however,  which  don't  have  an  initial special character.
  418.      Hint:  you  could  say   open(LOG,'logfile')   rather   than
  419.      open(log,'logfile').    Using   uppercase  filehandles  also
  420.      improves readability and protects  you  from  conflict  with
  421.      future  reserved  words.)  Case IS significant--"FOO", "Foo"
  422.      and "foo" are all different names.  Names which start with a
  423.      letter may also contain digits and underscores.  Names which
  424.      do not start with a letter are  limited  to  one  character,
  425.      e.g.  "$%" or "$$".  (Most of the one character names have a
  426.      predefined significance to perl.  More later.)
  427.  
  428.      Numeric literals are specified in any of the usual  floating
  429.      point or integer formats:
  430.  
  431.          12345
  432.          12345.67
  433.          .23E-10
  434.          0xffff     # hex
  435.          0377  # octal
  436.  
  437.      String literals are delimited by  either  single  or  double
  438.      quotes.   They  work  much  like shell quotes: double-quoted
  439.      string literals are subject to backslash and  variable  sub-
  440.      stitution;  single-quoted strings are not (except for \' and
  441.      \\).  The usual backslash rules apply for making  characters
  442.      such  as  newline,  tab,  etc.,  as well as some more exotic
  443.      forms:
  444.  
  445.           \t        tab
  446.           \n        newline
  447.           \r        return
  448.           \f        form feed
  449.           \b        backspace
  450.           \a        alarm (bell)
  451.           \e        escape
  452.           \033      octal char
  453.           \x1b      hex char
  454.           \c[       control char
  455.           \l        lowercase next char
  456.           \u        uppercase next char
  457.           \L        lowercase till \E
  458.           \U        uppercase till \E
  459.           \E        end case modification
  460.  
  461.      You can also embed newlines directly in your  strings,  i.e.
  462.      they  can  end on a different line than they begin.  This is
  463.      nice, but if you forget your trailing quote, the error  will
  464.      not be reported until perl finds another line containing the
  465.      quote character, which may be much further on in the script.
  466.      Variable  substitution  inside  strings is limited to scalar
  467.      variables, normal array values, and array slices.  (In other
  468.      words,  identifiers  beginning  with  $ or @, followed by an
  469.      optional bracketed expression as a subscript.) The following
  470.      code segment prints out "The price is $100."
  471.  
  472.          $Price = '$100';               # not interpreted
  473.          print "The price is $Price.\n";# interpreted
  474.  
  475.      Note that you can put curly brackets around  the  identifier
  476.      to  delimit it from following alphanumerics.  Also note that
  477.      a single quoted string must be separated  from  a  preceding
  478.      word  by a space, since single quote is a valid character in
  479.      an identifier (see Packages).
  480.  
  481.      Two  special  literals  are  __LINE__  and  __FILE__,  which
  482.      represent the current line number and filename at that point
  483.      in your program.  They may only be used as separate  tokens;
  484.      they  will  not  be interpolated into strings.  In addition,
  485.      the token __END__ may be used to indicate the logical end of
  486.      the  script  before  the  actual end of file.  Any following
  487.      text is ignored (but may be read via the  DATA  filehandle).
  488.      The  two  control  characters  ^D  and  ^Z  are synonyms for
  489.      __END__.
  490.  
  491.      A word that doesn't have any  other  interpretation  in  the
  492.      grammar  will  be  treated as if it had single quotes around
  493.      it.  For this purpose, a word consists only of  alphanumeric
  494.      characters  and underline, and must start with an alphabetic
  495.      character.  As with filehandles and labels, a bare word that
  496.      consists  entirely  of lowercase letters risks conflict with
  497.      future reserved words, and if you use the  -w  switch,  Perl
  498.      will warn you about any such words.
  499.  
  500.      Array values are interpolated into double-quoted strings  by
  501.      joining  all  the  elements  of the array with the delimiter
  502.      specified in the $" variable, space by default.   (Since  in
  503.      versions  of  perl  prior  to  3.0 the @ character was not a
  504.      metacharacter in double-quoted strings, the interpolation of
  505.      @array,   $array[EXPR],   @array[LIST],   $array{EXPR},   or
  506.      @array{LIST} only happens if array is  referenced  elsewhere
  507.      in   the  program  or  is  predefined.)  The  following  are
  508.      equivalent:
  509.  
  510.           $temp = join($",@ARGV);
  511.           system "echo $temp";
  512.  
  513.           system "echo @ARGV";
  514.  
  515.      Within search patterns (which  also  undergo  double-quotish
  516.      substitution)  there  is a bad ambiguity:  Is /$foo[bar]/ to
  517.      be interpreted as /${foo}[bar]/ (where [bar] is a  character
  518.      class for the regular expression) or as /${foo[bar]}/ (where
  519.      [bar] is the subscript to  array  @foo)?   If  @foo  doesn't
  520.      otherwise  exist, then it's obviously a character class.  If
  521.      @foo exists, perl takes a good guess  about  [bar],  and  is
  522.      almost  always  right.  If it does guess wrong, or if you're
  523.      just plain paranoid, you can force the  correct  interpreta-
  524.      tion with curly brackets as above.
  525.  
  526.      A line-oriented form of quoting is based on the shell  here-
  527.      is syntax.  Following a << you specify a string to terminate
  528.      the quoted material, and all  lines  following  the  current
  529.      line  down  to  the  terminating string are the value of the
  530.      item.  The terminating string may be either an identifier (a
  531.      word),  or  some quoted text.  If quoted, the type of quotes
  532.      you use determines the treatment of the  text,  just  as  in
  533.      regular  quoting.   An unquoted identifier works like double
  534.      quotes.  There must be no space between the << and the iden-
  535.      tifier.   (If  you  put a space it will be treated as a null
  536.      identifier, which is valid,  and  matches  the  first  blank
  537.      line--see  Merry  Christmas  example below.) The terminating
  538.      string must appear by itself (unquoted and with no surround-
  539.      ing whitespace) on the terminating line.
  540.  
  541.           print <<EOF;        # same as above
  542.      The price is $Price.
  543.      EOF
  544.  
  545.           print <<"EOF";      # same as above
  546.      The price is $Price.
  547.      EOF
  548.  
  549.           print << x 10;      # null identifier is delimiter
  550.      Merry Christmas!
  551.  
  552.           print <<`EOC`;      # execute commands
  553.      echo hi there
  554.      echo lo there
  555.      EOC
  556.  
  557.           print <<foo, <<bar; # you can stack them
  558.      I said foo.
  559.      foo
  560.      I said bar.
  561.      bar
  562.  
  563.      Array literals are denoted by separating  individual  values
  564.      by commas, and enclosing the list in parentheses:
  565.  
  566.           (LIST)
  567.  
  568.      In a context not requiring an array value, the value of  the
  569.      array literal is the value of the final element, as in the C
  570.      comma operator.  For example,
  571.  
  572.          @foo = ('cc', '-E', $bar);
  573.  
  574.      assigns the entire array value to array foo, but
  575.  
  576.          $foo = ('cc', '-E', $bar);
  577.  
  578.      assigns the value of variable bar  to  variable  foo.   Note
  579.      that the value of an actual array in a scalar context is the
  580.      length of the array; the following assigns to $foo the value
  581.      3:
  582.  
  583.          @foo = ('cc', '-E', $bar);
  584.          $foo = @foo;         # $foo gets 3
  585.  
  586.      You  may  have  an  optional  comma   before   the   closing
  587.      parenthesis of an array literal, so that you can say:
  588.  
  589.          @foo = (
  590.           1,
  591.           2,
  592.           3,
  593.          );
  594.  
  595.      When a LIST is  evaluated,  each  element  of  the  list  is
  596.      evaluated in an array context, and the resulting array value
  597.      is interpolated into LIST just as if each individual element
  598.      were a member of LIST.  Thus arrays lose their identity in a
  599.      LIST--the list
  600.  
  601.           (@foo,@bar,&SomeSub)
  602.  
  603.      contains all the elements of @foo followed by all  the  ele-
  604.      ments  of @bar, followed by all the elements returned by the
  605.      subroutine named SomeSub.
  606.  
  607.      A list value may also be subscripted like  a  normal  array.
  608.      Examples:
  609.  
  610.           $time = (stat($file))[8];     # stat returns array value
  611.           $digit = ('a','b','c','d','e','f')[$digit-10];
  612.           return (pop(@foo),pop(@foo))[0];
  613.  
  614.      Array lists may be assigned to if and only if  each  element
  615.      of the list is an lvalue:
  616.  
  617.          ($a, $b, $c) = (1, 2, 3);
  618.  
  619.          ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
  620.  
  621.      The final element may be an array or an associative array:
  622.  
  623.          ($a, $b, @rest) = split;
  624.          local($a, $b, %rest) = @_;
  625.  
  626.      You can actually put an array anywhere in the list, but  the
  627.      first  array  in  the  list will soak up all the values, and
  628.      anything after it will get a null value.  This may be useful
  629.      in a local().
  630.  
  631.      An associative array literal contains pairs of values to  be
  632.      interpreted as a key and a value:
  633.  
  634.          # same as map assignment above
  635.          %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
  636.  
  637.      Array assignment in a scalar context returns the  number  of
  638.      elements produced by the expression on the right side of the
  639.      assignment:
  640.  
  641.           $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
  642.  
  643.      There are several other pseudo-literals that you should know
  644.      about.    If  a  string  is  enclosed  by  backticks  (grave
  645.      accents), it first undergoes variable substitution just like
  646.      a  double  quoted  string.  It is then interpreted as a com-
  647.      mand, and the output of that command is  the  value  of  the
  648.      pseudo-literal,  like  in  a  shell.  In a scalar context, a
  649.      single string consisting of all the output is returned.   In
  650.      an  array  context,  an array of values is returned, one for
  651.      each line of output.  (You can set $/  to  use  a  different
  652.      line  terminator.)  The  command  is  executed each time the
  653.      pseudo-literal is evaluated.  The status value of  the  com-
  654.      mand  is  returned  in  $?  (see  Predefined  Names  for the
  655.      interpretation of $?).  Unlike in  csh,  no  translation  is
  656.      done  on  the return data--newlines remain newlines.  Unlike
  657.      in any of the shells, single quotes  do  not  hide  variable
  658.      names  in  the  command  from  interpretation.   To pass a $
  659.      through to the shell you need to hide it with a backslash.
  660.  
  661.      Evaluating a filehandle in angle brackets  yields  the  next
  662.      line  from  that file (newline included, so it's never false
  663.      until EOF, at which time an undefined  value  is  returned).
  664.      Ordinarily  you  must  assign  that value to a variable, but
  665.      there is one situation where an  automatic  assignment  hap-
  666.      pens.   If  (and only if) the input symbol is the only thing
  667.      inside the  conditional  of  a  while  loop,  the  value  is
  668.      automatically assigned to the variable "$_".  (This may seem
  669.      like an odd thing to you, but you'll use  the  construct  in
  670.      almost  every  perl script you write.) Anyway, the following
  671.      lines are equivalent to each other:
  672.  
  673.          while ($_ = <STDIN>) { print; }
  674.          while (<STDIN>) { print; }
  675.          for (;<STDIN>;) { print; }
  676.          print while $_ = <STDIN>;
  677.          print while <STDIN>;
  678.  
  679.      The filehandles STDIN, STDOUT  and  STDERR  are  predefined.
  680.      (The  filehandles  stdin,  stdout  and stderr will also work
  681.      except in packages, where they would be interpreted as local
  682.      identifiers  rather than global.) Additional filehandles may
  683.      be created with the open function.
  684.  
  685.      If a <FILEHANDLE> is used in a context that is  looking  for
  686.      an  array,  an  array  consisting  of all the input lines is
  687.      returned, one line per array element.  It's easy to  make  a
  688.      LARGE data space this way, so use with care.
  689.  
  690.      The null filehandle <> is special and can be used to emulate
  691.      the  behavior  of  sed  and awk.  Input from <> comes either
  692.      from standard input, or from each file listed on the command
  693.      line.   Here's how it works: the first time <> is evaluated,
  694.      the ARGV array is checked, and if it is  null,  $ARGV[0]  is
  695.      set to '-', which when opened gives you standard input.  The
  696.      ARGV array is then processed as a list  of  filenames.   The
  697.      loop
  698.  
  699.           while (<>) {
  700.                ...            # code for each line
  701.           }
  702.  
  703.      is equivalent to
  704.  
  705.           unshift(@ARGV, '-') if $#ARGV < $[;
  706.           while ($ARGV = shift) {
  707.                open(ARGV, $ARGV);
  708.                while (<ARGV>) {
  709.                     ...       # code for each line
  710.                }
  711.           }
  712.  
  713.      except that it isn't as cumbersome to say.  It  really  does
  714.      shift  array ARGV and put the current filename into variable
  715.      ARGV.  It also uses filehandle  ARGV  internally.   You  can
  716.      modify  @ARGV  before  the first <> as long as you leave the
  717.      first filename at the beginning of the array.  Line  numbers
  718.      ($.)  continue as if the input was one big happy file.  (But
  719.      see example under eof for how to reset line numbers on  each
  720.      file.)
  721.  
  722.      If you want to set @ARGV to your own list of files, go right
  723.      ahead.   If  you want to pass switches into your script, you
  724.      can put a loop on the front like this:
  725.  
  726.           while ($_ = $ARGV[0], /^-/) {
  727.                shift;
  728.               last if /^--$/;
  729.                /^-D(.*)/ && ($debug = $1);
  730.                /^-v/ && $verbose++;
  731.                ...       # other switches
  732.           }
  733.           while (<>) {
  734.                ...       # code for each line
  735.           }
  736.  
  737.      The <> symbol will return FALSE only once.  If you  call  it
  738.      again  after  this it will assume you are processing another
  739.      @ARGV list, and if you haven't set @ARGV,  will  input  from
  740.      STDIN.
  741.  
  742.      If the string inside the angle brackets is a reference to  a
  743.      scalar  variable  (e.g. <$foo>), then that variable contains
  744.      the name of the filehandle to input from.
  745.  
  746.      If the string inside angle brackets is not a filehandle,  it
  747.      is  interpreted  as  a  filename  pattern to be globbed, and
  748.      either an array of filenames or the  next  filename  in  the
  749.      list  is  returned,  depending  on  context.  One level of $
  750.      interpretation is done  first,  but  you  can't  say  <$foo>
  751.      because  that's  an  indirect filehandle as explained in the
  752.      previous paragraph.  You  could  insert  curly  brackets  to
  753.      force interpretation as a filename glob: <${foo}>.  Example:
  754.  
  755.           while (<*.c>) {
  756.                chmod 0644, $_;
  757.           }
  758.  
  759.      is equivalent to
  760.  
  761.           open(foo, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
  762.           while (<foo>) {
  763.                chop;
  764.                chmod 0644, $_;
  765.           }
  766.  
  767.      In fact, it's currently implemented that way.  (Which  means
  768.      it will not work on filenames with spaces in them unless you
  769.      have /bin/csh on your machine.) Of course, the shortest  way
  770.      to do the above is:
  771.  
  772.           chmod 0644, <*.c>;
  773.  
  774.      Syntax
  775.  
  776.      A perl script consists of a  sequence  of  declarations  and
  777.      commands.   The only things that need to be declared in perl
  778.      are report formats and subroutines.  See the sections  below
  779.      for  more information on those declarations.  All uninitial-
  780.      ized user-created objects are assumed to start with  a  null
  781.      or 0 value until they are defined by some explicit operation
  782.      such as assignment.  The sequence of  commands  is  executed
  783.      just once, unlike in sed and awk scripts, where the sequence
  784.      of commands is executed for each  input  line.   While  this
  785.      means  that  you must explicitly loop over the lines of your
  786.      input file (or files), it also means you have much more con-
  787.      trol  over  which files and which lines you look at.  (Actu-
  788.      ally, I'm lying--it is possible to do an implicit loop  with
  789.      either the -n or -p switch.)
  790.  
  791.      A declaration can be put anywhere a command can, but has  no
  792.      effect   on   the  execution  of  the  primary  sequence  of
  793.      commands--declarations all  take  effect  at  compile  time.
  794.      Typically  all  the declarations are put at the beginning or
  795.      the end of the script.
  796.  
  797.      Perl is, for the most part, a free-form language.  (The only
  798.      exception to this is format declarations, for fairly obvious
  799.      reasons.) Comments are indicated by  the  #  character,  and
  800.      extend  to the end of the line.  If you attempt to use /* */
  801.      C comments, it will be interpreted  either  as  division  or
  802.      pattern  matching,  depending  on  the context.  So don't do
  803.      that.
  804.  
  805.      Compound statements
  806.  
  807.      In perl, a sequence of commands may be treated as  one  com-
  808.      mand by enclosing it in curly brackets.  We will call this a
  809.      BLOCK.
  810.  
  811.      The following compound commands may be used to control flow:
  812.  
  813.           if (EXPR) BLOCK
  814.           if (EXPR) BLOCK else BLOCK
  815.           if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
  816.           LABEL while (EXPR) BLOCK
  817.           LABEL while (EXPR) BLOCK continue BLOCK
  818.           LABEL for (EXPR; EXPR; EXPR) BLOCK
  819.           LABEL foreach VAR (ARRAY) BLOCK
  820.           LABEL BLOCK continue BLOCK
  821.  
  822.      Note that, unlike C and Pascal, these are defined  in  terms
  823.      of BLOCKs, not statements.  This means that the curly brack-
  824.      ets are required--no dangling statements  allowed.   If  you
  825.      want  to write conditionals without curly brackets there are
  826.      several other ways to do it.  The following all do the  same
  827.      thing:
  828.  
  829.           if (!open(foo)) { die "Can't open $foo: $!"; }
  830.           die "Can't open $foo: $!" unless open(foo);
  831.           open(foo) || die "Can't open $foo: $!"; # foo or bust!
  832.           open(foo) ? 'hi mom' : die "Can't open $foo: $!";
  833.                          # a bit exotic, that last one
  834.  
  835.      The if  statement  is  straightforward.   Since  BLOCKs  are
  836.      always  bounded  by curly brackets, there is never any ambi-
  837.      guity about which if an else goes with.  If you  use  unless
  838.      in place of if, the sense of the test is reversed.
  839.  
  840.      The while statement  executes  the  block  as  long  as  the
  841.      expression  is true (does not evaluate to the null string or
  842.      0).  The LABEL is optional, and if present, consists  of  an
  843.      identifier  followed  by  a colon.  The LABEL identifies the
  844.      loop for the loop control statements next,  last,  and  redo
  845.      (see  below).   If  there  is a continue BLOCK, it is always
  846.      executed  just  before  the  conditional  is  about  to   be
  847.      evaluated  again,  similarly to the third part of a for loop
  848.      in C.  Thus it can be used to  increment  a  loop  variable,
  849.      even when the loop has been continued via the next statement
  850.      (similar to the C "continue" statement).
  851.  
  852.      If the word while is replaced by the word until,  the  sense
  853.      of the test is reversed, but the conditional is still tested
  854.      before the first iteration.
  855.  
  856.      In either the if or the while  statement,  you  may  replace
  857.      "(EXPR)"  with  a  BLOCK, and the conditional is true if the
  858.      value of the last command in that block is true.
  859.  
  860.      The for loop works  exactly  like  the  corresponding  while
  861.      loop:
  862.  
  863.           for ($i = 1; $i < 10; $i++) {
  864.                ...
  865.           }
  866.  
  867.      is the same as
  868.  
  869.           $i = 1;
  870.           while ($i < 10) {
  871.                ...
  872.           } continue {
  873.                $i++;
  874.           }
  875.  
  876.      The foreach loop iterates over a normal array value and sets
  877.      the  variable  VAR  to be each element of the array in turn.
  878.      The variable is implicitly local to the  loop,  and  regains
  879.      its  former value upon exiting the loop.  The "foreach" key-
  880.      word is actually identical to the "for" keyword, so you  can
  881.      use  "foreach" for readability or "for" for brevity.  If VAR
  882.      is omitted, $_ is set to each value.  If ARRAY is an  actual
  883.      array  (as  opposed  to  an  expression  returning  an array
  884.      value), you can modify each element of the array by  modify-
  885.      ing VAR inside the loop.  Examples:
  886.  
  887.           for (@ary) { s/foo/bar/; }
  888.  
  889.           foreach $elem (@elements) {
  890.                $elem *= 2;
  891.           }
  892.  
  893.           for ((10,9,8,7,6,5,4,3,2,1,'BOOM')) {
  894.                print $_, "\n"; sleep(1);
  895.           }
  896.  
  897.           for (1..15) { print "Merry Christmas\n"; }
  898.  
  899.           foreach $item (split(/:[\\\n:]*/, $ENV{'TERMCAP'})) {
  900.                print "Item: $item\n";
  901.           }
  902.  
  903.      The BLOCK by itself (labeled or not) is equivalent to a loop
  904.      that  executes  once.  Thus you can use any of the loop con-
  905.      trol statements in it to leave or restart  the  block.   The
  906.      continue  block is optional.  This construct is particularly
  907.      nice for doing case structures.
  908.  
  909.           foo: {
  910.                if (/^abc/) { $abc = 1; last foo; }
  911.                if (/^def/) { $def = 1; last foo; }
  912.                if (/^xyz/) { $xyz = 1; last foo; }
  913.                $nothing = 1;
  914.           }
  915.  
  916.      There is no official switch statement in perl, because there
  917.      are  already several ways to write the equivalent.  In addi-
  918.      tion to the above, you could write
  919.  
  920.           foo: {
  921.                $abc = 1, last foo  if /^abc/;
  922.                $def = 1, last foo  if /^def/;
  923.                $xyz = 1, last foo  if /^xyz/;
  924.                $nothing = 1;
  925.           }
  926.  
  927.      or
  928.  
  929.           foo: {
  930.                /^abc/ && do { $abc = 1; last foo; };
  931.                /^def/ && do { $def = 1; last foo; };
  932.                /^xyz/ && do { $xyz = 1; last foo; };
  933.                $nothing = 1;
  934.           }
  935.  
  936.      or
  937.  
  938.           foo: {
  939.                /^abc/ && ($abc = 1, last foo);
  940.                /^def/ && ($def = 1, last foo);
  941.                /^xyz/ && ($xyz = 1, last foo);
  942.                $nothing = 1;
  943.           }
  944.  
  945.      or even
  946.  
  947.           if (/^abc/)
  948.                { $abc = 1; }
  949.           elsif (/^def/)
  950.                { $def = 1; }
  951.           elsif (/^xyz/)
  952.                { $xyz = 1; }
  953.           else
  954.                {$nothing = 1;}
  955.  
  956.      As it happens, these  are  all  optimized  internally  to  a
  957.      switch  structure,  so  perl  jumps  directly to the desired
  958.      statement, and you needn't worry about perl executing a  lot
  959.      of  unnecessary  statements  when  you  have  a string of 50
  960.      elsifs, as long as you are testing the  same  simple  scalar
  961.      variable  using  ==,  eq, or pattern matching as above.  (If
  962.      you're curious as to whether the optimizer has done this for
  963.      a  particular  case statement, you can use the -D1024 switch
  964.      to list the syntax tree before execution.)
  965.  
  966.      Simple statements
  967.  
  968.      The only kind of simple statement is an expression evaluated
  969.      for  its  side effects.  Every expression (simple statement)
  970.      must be terminated with a semicolon.  Note that this is like
  971.      C, but unlike Pascal (and awk).
  972.  
  973.      Any simple statement may optionally be followed by a  single
  974.      modifier, just before the terminating semicolon.  The possi-
  975.      ble modifiers are:
  976.  
  977.           if EXPR
  978.           unless EXPR
  979.           while EXPR
  980.           until EXPR
  981.  
  982.      The if and unless modifiers  have  the  expected  semantics.
  983.      The  while and until modifiers also have the expected seman-
  984.      tics (conditional evaluated first), except when applied to a
  985.      do-BLOCK or a do-SUBROUTINE command, in which case the block
  986.      executes once before the conditional is evaluated.  This  is
  987.      so that you can write loops like:
  988.  
  989.           do {
  990.                $_ = <STDIN>;
  991.                ...
  992.           } until $_ eq ".\n";
  993.  
  994.      (See the do operator below.  Note also that the loop control
  995.      commands  described  later  will NOT work in this construct,
  996.      since modifiers don't take loop labels.  Sorry.)
  997.  
  998.      Expressions
  999.  
  1000.      Since perl expressions work almost exactly  like  C  expres-
  1001.      sions, only the differences will be mentioned here.
  1002.  
  1003.      Here's what perl has that C doesn't:
  1004.  
  1005.      **      The exponentiation operator.
  1006.  
  1007.      **=     The exponentiation assignment operator.
  1008.  
  1009.      ()      The null list, used to initialize an array to null.
  1010.  
  1011.      .       Concatenation of two strings.
  1012.  
  1013.      .=      The concatenation assignment operator.
  1014.  
  1015.      eq      String equality (== is  numeric  equality).   For  a
  1016.              mnemonic  just  think  of "eq" as a string.  (If you
  1017.              are used to the awk behavior of using == for  either
  1018.              string or numeric equality based on the current form
  1019.              of the comparands, beware!   You  must  be  explicit
  1020.              here.)
  1021.  
  1022.      ne      String inequality (!= is numeric inequality).
  1023.  
  1024.      lt      String less than.
  1025.  
  1026.      gt      String greater than.
  1027.  
  1028.      le      String less than or equal.
  1029.  
  1030.      ge      String greater than or equal.
  1031.  
  1032.      cmp     String comparison, returning -1, 0, or 1.
  1033.  
  1034.      <=>     Numeric comparison, returning -1, 0, or 1.
  1035.  
  1036.      =~      Certain operations search or modify the string  "$_"
  1037.              by default.  This operator makes that kind of opera-
  1038.              tion work on some other string.  The right  argument
  1039.              is  a  search pattern, substitution, or translation.
  1040.              The  left  argument  is  what  is  supposed  to   be
  1041.              searched,  substituted, or translated instead of the
  1042.              default "$_".  The return value indicates  the  suc-
  1043.              cess of the operation.  (If the right argument is an
  1044.              expression other than a  search  pattern,  substitu-
  1045.              tion,  or translation, it is interpreted as a search
  1046.              pattern at run time.  This is less efficient than an
  1047.              explicit  search, since the pattern must be compiled
  1048.              every time the expression is  evaluated.)  The  pre-
  1049.              cedence  of  this operator is lower than unary minus
  1050.              and autoincrement/decrement, but higher than  every-
  1051.              thing else.
  1052.  
  1053.      !~      Just like =~ except the return value is negated.
  1054.  
  1055.      x       The repetition operator.  Returns a string  consist-
  1056.              ing of the left operand repeated the number of times
  1057.              specified by the right operand.  In  an  array  con-
  1058.              text,  if  the  left operand is a list in parens, it
  1059.              repeats the list.
  1060.  
  1061.                   print '-' x 80;          # print row of dashes
  1062.                   print '-' x80;      # illegal, x80 is identifier
  1063.  
  1064.                   print "\t" x ($tab/8), ' ' x ($tab%8);  # tab over
  1065.  
  1066.                   @ones = (1) x 80;        # an array of 80 1's
  1067.                   @ones = (5) x @ones;          # set all elements to 5
  1068.  
  1069.      x=      The repetition assignment operator.  Only  works  on
  1070.              scalars.
  1071.  
  1072.      ..      The range operator, which is  really  two  different
  1073.              operators  depending  on  the  context.  In an array
  1074.              context, returns an array  of  values  counting  (by
  1075.              ones)  from the left value to the right value.  This
  1076.              is useful for writing "for (1..10)"  loops  and  for
  1077.              doing slice operations on arrays.
  1078.  
  1079.              In a scalar context, ..  returns  a  boolean  value.
  1080.              The  operator  is bistable, like a flip-flop..  Each
  1081.              .. operator maintains its own boolean state.  It  is
  1082.              false  as  long  as its left operand is false.  Once
  1083.              the left operand is true, the range  operator  stays
  1084.              true  until  the  right operand is true, AFTER which
  1085.              the range operator becomes false again.  (It doesn't
  1086.              become  false  till the next time the range operator
  1087.              is evaluated.  It  can  become  false  on  the  same
  1088.              evaluation it became true, but it still returns true
  1089.              once.) The right operand is not evaluated while  the
  1090.              operator  is  in  the  "false"  state,  and the left
  1091.              operand is not evaluated while the  operator  is  in
  1092.              the  "true"  state.   The scalar .. operator is pri-
  1093.              marily intended for doing line number  ranges  after
  1094.              the fashion of sed or awk.  The precedence is a lit-
  1095.              tle lower than || and &&.   The  value  returned  is
  1096.              either  the  null  string  for  false, or a sequence
  1097.              number (beginning with 1) for  true.   The  sequence
  1098.              number  is  reset  for  each range encountered.  The
  1099.              final sequence number in a range has the string 'E0'
  1100.              appended  to  it,  which  doesn't affect its numeric
  1101.              value, but gives you something to search for if  you
  1102.              want  to  exclude the endpoint.  You can exclude the
  1103.              beginning point by waiting for the  sequence  number
  1104.              to  be  greater than 1.  If either operand of scalar
  1105.              .. is static, that operand is implicitly compared to
  1106.              the $. variable, the current line number.  Examples:
  1107.  
  1108.              As a scalar operator:
  1109.                  if (101 .. 200) { print; }     # print 2nd hundred lines
  1110.  
  1111.                  next line if (1 .. /^$/); # skip header lines
  1112.  
  1113.                  s/^/> / if (/^$/ .. eof());    # quote body
  1114.  
  1115.              As an array operator:
  1116.                  for (101 .. 200) { print; }    # print $_ 100 times
  1117.  
  1118.                  @foo = @foo[$[ .. $#foo]; # an expensive no-op
  1119.                  @foo = @foo[$#foo-4 .. $#foo]; # slice last 5 items
  1120.  
  1121.      -x      A file test.  This unary operator  takes  one  argu-
  1122.              ment,  either  a filename or a filehandle, and tests
  1123.              the associated file to  see  if  something  is  true
  1124.              about  it.   If  the  argument is omitted, tests $_,
  1125.              except for -t, which tests STDIN.  It returns 1  for
  1126.              true and '' for false, or the undefined value if the
  1127.              file doesn't exist.  Precedence is higher than logi-
  1128.              cal  and relational operators, but lower than arith-
  1129.              metic operators.  The operator may be any of:
  1130.  
  1131.                   -r   File is readable by effective uid.
  1132.                   -w   File is writable by effective uid.
  1133.                   -x   File is executable by effective uid.
  1134.                   -o   File is owned by effective uid.
  1135.                   -R   File is readable by real uid.
  1136.                   -W   File is writable by real uid.
  1137.                   -X   File is executable by real uid.
  1138.                   -O   File is owned by real uid.
  1139.                   -e   File exists.
  1140.                   -z   File has zero size.
  1141.                   -s   File has non-zero size (returns size).
  1142.                   -f   File is a plain file.
  1143.                   -d   File is a directory.
  1144.                   -l   File is a symbolic link.
  1145.                   -p   File is a named pipe (FIFO).
  1146.                   -S   File is a socket.
  1147.                   -b   File is a block special file.
  1148.                   -c   File is a character special file.
  1149.                   -u   File has setuid bit set.
  1150.                   -g   File has setgid bit set.
  1151.                   -k   File has sticky bit set.
  1152.                   -t   Filehandle is opened to a tty.
  1153.                   -T   File is a text file.
  1154.                   -B   File is a binary file (opposite of -T).
  1155.                   -M   Age of file in days when script started.
  1156.                   -A   Same for access time.
  1157.                   -C   Same for inode change time.
  1158.  
  1159.              The interpretation of the file permission  operators
  1160.              -r,  -R,  -w,  -W,  -x and -X is based solely on the
  1161.              mode of the file and the uids and gids of the  user.
  1162.              There  may be other reasons you can't actually read,
  1163.              write or execute the file.  Also note that, for  the
  1164.              superuser, -r, -R, -w and -W always return 1, and -x
  1165.              and -X return 1 if any execute bit  is  set  in  the
  1166.              mode.  Scripts run by the superuser may thus need to
  1167.              do a stat() in order to determine the actual mode of
  1168.              the  file,  or  temporarily set the uid to something
  1169.              else.
  1170.  
  1171.              Example:
  1172.  
  1173.                   while (<>) {
  1174.                        chop;
  1175.                        next unless -f $_;  # ignore specials
  1176.                        ...
  1177.                   }
  1178.  
  1179.              Note that -s/a/b/ does not do  a  negated  substitu-
  1180.              tion.   Saying  -exp($foo)  still works as expected,
  1181.              however--only single letters following a  minus  are
  1182.              interpreted as file tests.
  1183.  
  1184.              The -T and -B switches work as follows.   The  first
  1185.              block  or so of the file is examined for odd charac-
  1186.              ters such as strange control  codes  or  metacharac-
  1187.              ters.   If too many odd characters (>10%) are found,
  1188.              it's a -B file, otherwise it's a -T file.  Also, any
  1189.              file  containing  null  in  the  first block is con-
  1190.              sidered a binary file.  If -T or -B  is  used  on  a
  1191.              filehandle,  the  current  stdio  buffer is examined
  1192.              rather than the first block.  Both -T and -B  return
  1193.              TRUE on a null file, or a file at EOF when testing a
  1194.              filehandle.
  1195.  
  1196.      If any of the file tests (or either stat operator) are given
  1197.      the  special  filehandle consisting of a solitary underline,
  1198.      then the stat structure of the previous file test  (or  stat
  1199.      operator) is used, saving a system call.  (This doesn't work
  1200.      with -t, and you need to remember that  lstat  and  -l  will
  1201.      leave  values  in  the stat structure for the symbolic link,
  1202.      not the real file.) Example:
  1203.  
  1204.           print "Can do.\n" if -r $a || -w _ || -x _;
  1205.  
  1206.           stat($filename);
  1207.           print "Readable\n" if -r _;
  1208.           print "Writable\n" if -w _;
  1209.           print "Executable\n" if -x _;
  1210.           print "Setuid\n" if -u _;
  1211.           print "Setgid\n" if -g _;
  1212.           print "Sticky\n" if -k _;
  1213.           print "Text\n" if -T _;
  1214.           print "Binary\n" if -B _;
  1215.  
  1216.      Here is what C has that perl doesn't:
  1217.  
  1218.      unary &     Address-of operator.
  1219.  
  1220.      unary *     Dereference-address operator.
  1221.  
  1222.      (TYPE)      Type casting operator.
  1223.  
  1224.      Like C, perl does a certain amount of expression  evaluation
  1225.      at  compile  time,  whenever  it  determines that all of the
  1226.      arguments to  an  operator  are  static  and  have  no  side
  1227.      effects.   In  particular,  string  concatenation happens at
  1228.      compile time between literals that don't do variable substi-
  1229.      tution.   Backslash  interpretation  also happens at compile
  1230.      time.  You can say
  1231.  
  1232.           'Now is the time for all' . "\n" .
  1233.           'good men to come to.'
  1234.  
  1235.      and this all reduces to one string internally.
  1236.  
  1237.      The autoincrement operator has a little extra built-in magic
  1238.      to it.  If you increment a variable that is numeric, or that
  1239.      has ever been used in a numeric context, you  get  a  normal
  1240.      increment.   If, however, the variable has only been used in
  1241.      string contexts since it was set, and has a  value  that  is
  1242.      not  null  and  matches the pattern /^[a-zA-Z]*[0-9]*$/, the
  1243.      increment is done as a  string,  preserving  each  character
  1244.      within its range, with carry:
  1245.  
  1246.           print ++($foo = '99');   # prints '100'
  1247.           print ++($foo = 'a0');   # prints 'a1'
  1248.           print ++($foo = 'Az');   # prints 'Ba'
  1249.           print ++($foo = 'zz');   # prints 'aaa'
  1250.  
  1251.      The autodecrement is not magical.
  1252.  
  1253.      The range operator (in an array context) makes  use  of  the
  1254.      magical  autoincrement  algorithm if the minimum and maximum
  1255.      are strings.  You can say
  1256.  
  1257.           @alphabet = ('A' .. 'Z');
  1258.  
  1259.      to get all the letters of the alphabet, or
  1260.  
  1261.           $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
  1262.  
  1263.      to get a hexadecimal digit, or
  1264.  
  1265.           @z2 = ('01' .. '31');  print @z2[$mday];
  1266.  
  1267.      to get dates with leading zeros.  (If the final value speci-
  1268.      fied is not in the sequence that the magical increment would
  1269.      produce, the sequence goes until the  next  value  would  be
  1270.      longer than the final value specified.)
  1271.  
  1272.      The || and && operators differ from C's in that, rather than
  1273.      returning  0  or  1,  they  return the last value evaluated.
  1274.      Thus, a portable way to find out the  home  directory  might
  1275.      be:
  1276.  
  1277.           $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
  1278.               (getpwuid($<))[7] || die "You're homeless!\n";
  1279.  
  1280.      Along with the literals and variables mentioned earlier, the
  1281.      operations in the following section can serve as terms in an
  1282.      expression.  Some of these operations  take  a  LIST  as  an
  1283.      argument.   Such  a  list  can consist of any combination of
  1284.      scalar arguments or array values; the array values  will  be
  1285.      included  in  the  list  as  if each individual element were
  1286.      interpolated at that point in the  list,  forming  a  longer
  1287.      single-dimensional array value.  Elements of the LIST should
  1288.      be separated by commas.  If an operation is listed both with
  1289.      and  without  parentheses around its arguments, it means you
  1290.      can either use it as a unary operator or as a function call.
  1291.      To  use  it  as  a function call, the next token on the same
  1292.      line must be a left parenthesis.  (There may be  intervening
  1293.      white  space.)  Such a function then has highest precedence,
  1294.      as you would expect from a function.   If  any  token  other
  1295.      than  a  left parenthesis follows, then it is a unary opera-
  1296.      tor, with a precedence depending only on  whether  it  is  a
  1297.      LIST  operator  or  not.   LIST  operators  have lowest pre-
  1298.      cedence.   All  other  unary  operators  have  a  precedence
  1299.      greater  than  relational operators but less than arithmetic
  1300.      operators.  See the section on Precedence.
  1301.  
  1302.      /PATTERN/
  1303.              See m/PATTERN/.
  1304.  
  1305.      ?PATTERN?
  1306.              This is just like the /pattern/ search, except  that
  1307.              it  matches  only  once  between  calls to the reset
  1308.              operator.  This is a useful  optimization  when  you
  1309.              only  want  to see the first occurrence of something
  1310.              in each file of a set of files, for instance.   Only
  1311.              ?? patterns local to the current package are reset.
  1312.  
  1313.      accept(NEWSOCKET,GENERICSOCKET)
  1314.              Does the same thing  that  the  accept  system  call
  1315.              does.   Returns  true  if it succeeded, false other-
  1316.              wise.  See example in section on  Interprocess  Com-
  1317.              munication.
  1318.  
  1319.      alarm(SECONDS)
  1320.      alarm SECONDS
  1321.              Arranges to have a SIGALRM delivered to this process
  1322.              after  the  specified  number  of  seconds (minus 1,
  1323.              actually) have elapsed.  Thus, alarm(15) will  cause
  1324.              a  SIGALRM at some point more than 14 seconds in the
  1325.              future.  Only one timer may  be  counting  at  once.
  1326.              Each  call disables the previous timer, and an argu-
  1327.              ment of 0 may be supplied  to  cancel  the  previous
  1328.              timer  without  starting  a  new  one.  The returned
  1329.              value is the amount of time remaining on the  previ-
  1330.              ous timer.
  1331.  
  1332.      atan2(Y,X)
  1333.              Returns the arctangent of Y/X in the  range  -PI  to
  1334.              PI.
  1335.  
  1336.      bind(SOCKET,NAME)
  1337.              Does the same thing that the bind system call  does.
  1338.              Returns true if it succeeded, false otherwise.  NAME
  1339.              should be a packed address of the  proper  type  for
  1340.              the  socket.  See example in section on Interprocess
  1341.              Communication.
  1342.  
  1343.      binmode(FILEHANDLE)
  1344.      binmode FILEHANDLE
  1345.              Arranges for the file to be read in "binary" mode in
  1346.              operating  systems  that  distinguish between binary
  1347.              and text files.  Files that are not read  in  binary
  1348.              mode  have CR LF sequences translated to LF on input
  1349.              and LF translated to CR LF on output.   Binmode  has
  1350.              no  effect  under Unix.  If FILEHANDLE is an expres-
  1351.              sion, the value is taken as the name of the filehan-
  1352.              dle.
  1353.  
  1354.      caller(EXPR)
  1355.      caller  Returns the context of the current subroutine call:
  1356.  
  1357.                   ($package,$filename,$line) = caller;
  1358.  
  1359.              With EXPR, returns some extra information  that  the
  1360.              debugger  uses to print a stack trace.  The value of
  1361.              EXPR indicates how  many  call  frames  to  go  back
  1362.              before the current one.
  1363.  
  1364.      chdir(EXPR)
  1365.      chdir EXPR
  1366.              Changes the working directory to EXPR, if  possible.
  1367.              If  EXPR  is  omitted,  changes  to  home directory.
  1368.              Returns 1 upon success, 0  otherwise.   See  example
  1369.              under die.
  1370.  
  1371.      chmod(LIST)
  1372.      chmod LIST
  1373.              Changes the permissions of a  list  of  files.   The
  1374.              first  element  of  the  list  must be the numerical
  1375.              mode.  Returns  the  number  of  files  successfully
  1376.              changed.
  1377.  
  1378.                   $cnt = chmod 0755, 'foo', 'bar';
  1379.                   chmod 0755, @executables;
  1380.  
  1381.      chop(LIST)
  1382.      chop(VARIABLE)
  1383.      chop VARIABLE
  1384.      chop    Chops off the last character of a string and returns
  1385.              the  character  chopped.   It's  used  primarily  to
  1386.              remove the newline from the end of an input  record,
  1387.              but  is  much  more efficient than s/\n// because it
  1388.              neither scans nor copies the string.  If VARIABLE is
  1389.              omitted, chops $_.  Example:
  1390.  
  1391.                   while (<>) {
  1392.                        chop;     # avoid \n on last field
  1393.                        @array = split(/:/);
  1394.                        ...
  1395.                   }
  1396.  
  1397.              You can actually chop  anything  that's  an  lvalue,
  1398.              including an assignment:
  1399.  
  1400.                   chop($cwd = `pwd`);
  1401.                   chop($answer = <STDIN>);
  1402.  
  1403.              If you chop a list, each element is  chopped.   Only
  1404.              the value of the last chop is returned.
  1405.  
  1406.      chown(LIST)
  1407.      chown LIST
  1408.              Changes the owner (and group) of a  list  of  files.
  1409.              The  first  two  elements  of  the  list must be the
  1410.              NUMERICAL uid and gid, in that order.   Returns  the
  1411.              number of files successfully changed.
  1412.  
  1413.                   $cnt = chown $uid, $gid, 'foo', 'bar';
  1414.                   chown $uid, $gid, @filenames;
  1415.  
  1416.              Here's an example that looks up non-numeric uids  in
  1417.              the passwd file:
  1418.  
  1419.                   print "User: ";
  1420.                   $user = <STDIN>;
  1421.                   chop($user);
  1422.                   print "Files: "
  1423.                   $pattern = <STDIN>;
  1424.                   chop($pattern);
  1425.                   open(pass, '/etc/passwd')
  1426.                        || die "Can't open passwd: $!\n";
  1427.                   while (<pass>) {
  1428.                        ($login,$pass,$uid,$gid) = split(/:/);
  1429.                        $uid{$login} = $uid;
  1430.                        $gid{$login} = $gid;
  1431.                   }
  1432.                   @ary = <${pattern}>;     # get filenames
  1433.                   if ($uid{$user} eq '') {
  1434.                        die "$user not in passwd file";
  1435.                   }
  1436.                   else {
  1437.                        chown $uid{$user}, $gid{$user}, @ary;
  1438.                   }
  1439.  
  1440.      chroot(FILENAME)
  1441.      chroot FILENAME
  1442.              Does the same as the system call of that  name.   If
  1443.              you  don't  know what it does, don't worry about it.
  1444.              If FILENAME is omitted, does chroot to $_.
  1445.  
  1446.      close(FILEHANDLE)
  1447.      close FILEHANDLE
  1448.              Closes the file or pipe  associated  with  the  file
  1449.              handle.   You  don't have to close FILEHANDLE if you
  1450.              are immediately going to  do  another  open  on  it,
  1451.              since  open will close it for you.  (See open.) How-
  1452.              ever, an explicit close on an input file resets  the
  1453.              line  counter ($.), while the implicit close done by
  1454.              open does not.  Also, closing a pipe will  wait  for
  1455.              the  process  executing  on the pipe to complete, in
  1456.              case you want to look at  the  output  of  the  pipe
  1457.              afterwards.  Closing a pipe explicitly also puts the
  1458.              status value of the command into $?.  Example:
  1459.  
  1460.                   open(OUTPUT, '|sort >foo');   # pipe to sort
  1461.                   ...  # print stuff to output
  1462.                   close OUTPUT;       # wait for sort to finish
  1463.                   open(INPUT, 'foo'); # get sort's results
  1464.  
  1465.              FILEHANDLE may be an expression  whose  value  gives
  1466.              the real filehandle name.
  1467.  
  1468.      closedir(DIRHANDLE)
  1469.      closedir DIRHANDLE
  1470.              Closes a directory opened by opendir().
  1471.  
  1472.      connect(SOCKET,NAME)
  1473.              Does the same thing that  the  connect  system  call
  1474.              does.   Returns  true  if it succeeded, false other-
  1475.              wise.  NAME should  be  a  package  address  of  the
  1476.              proper  type for the socket.  See example in section
  1477.              on Interprocess Communication.
  1478.  
  1479.      cos(EXPR)
  1480.      cos EXPR
  1481.              Returns the cosine of EXPR (expressed  in  radians).
  1482.              If EXPR is omitted takes cosine of $_.
  1483.  
  1484.      crypt(PLAINTEXT,SALT)
  1485.              Encrypts a string exactly like the crypt()  function
  1486.              in  the C library.  Useful for checking the password
  1487.              file for lousy passwords.   Only  the  guys  wearing
  1488.              white hats should do this.
  1489.  
  1490.      dbmclose(ASSOC_ARRAY)
  1491.      dbmclose ASSOC_ARRAY
  1492.              Breaks the binding between a dbm file and an associ-
  1493.              ative  array.   The values remaining in the associa-
  1494.              tive array are meaningless unless you happen to want
  1495.              to  know  what  was  in  the cache for the dbm file.
  1496.              This function is only useful if you have ndbm.
  1497.  
  1498.      dbmopen(ASSOC,DBNAME,MODE)
  1499.              This binds a dbm or  ndbm  file  to  an  associative
  1500.              array.   ASSOC is the name of the associative array.
  1501.              (Unlike normal open, the first  argument  is  NOT  a
  1502.              filehandle,  even though it looks like one).  DBNAME
  1503.              is the name of the database  (without  the  .dir  or
  1504.              .pag extension).  If the database does not exist, it
  1505.              is created with protection  specified  by  MODE  (as
  1506.              modified  by  the  umask).  If your system only sup-
  1507.              ports the older dbm functions, you may perform  only
  1508.              one  dbmopen  in  your  program.  If your system has
  1509.              neither dbm nor ndbm,  calling  dbmopen  produces  a
  1510.              fatal error.
  1511.  
  1512.              Values assigned to the associative  array  prior  to
  1513.              the  dbmopen  are  lost.  A certain number of values
  1514.              from the dbm file are cached in memory.  By  default
  1515.              this number is 64, but you can increase it by preal-
  1516.              locating that number of garbage entries in the asso-
  1517.              ciative array before the dbmopen.  You can flush the
  1518.              cache if necessary with the reset command.
  1519.  
  1520.              If you don't have write access to the dbm file,  you
  1521.              can  only  read associative array variables, not set
  1522.              them.  If you want to test whether  you  can  write,
  1523.              either  use  file tests or try setting a dummy array
  1524.              entry inside an eval, which will trap the error.
  1525.  
  1526.              Note that functions such as keys() and values()  may
  1527.              return  huge  array  values  when  used on large dbm
  1528.              files.  You may prefer to use the each() function to
  1529.              iterate over large dbm files.  Example:
  1530.  
  1531.                   # print out history file offsets
  1532.                   dbmopen(HIST,'/usr/lib/news/history',0666);
  1533.                   while (($key,$val) = each %HIST) {
  1534.                        print $key, ' = ', unpack('L',$val), "\n";
  1535.                   }
  1536.                   dbmclose(HIST);
  1537.  
  1538.      defined(EXPR)
  1539.      defined EXPR
  1540.              Returns a boolean value saying  whether  the  lvalue
  1541.              EXPR  has  a  real  value  or  not.  Many operations
  1542.              return the undefined value under exceptional  condi-
  1543.              tions,  such as end of file, uninitialized variable,
  1544.              system error and such.  This function allows you  to
  1545.              distinguish  between  an undefined null string and a
  1546.              defined  null  string  with  operations  that  might
  1547.              return a real null string, in particular referencing
  1548.              elements of an array.  You may also check to see  if
  1549.              arrays  or  subroutines  exist.   Use  on predefined
  1550.              variables is not  guaranteed  to  produce  intuitive
  1551.              results.  Examples:
  1552.  
  1553.                   print if defined $switch{'D'};
  1554.                   print "$val\n" while defined($val = pop(@ary));
  1555.                   die "Can't readlink $sym: $!"
  1556.                        unless defined($value = readlink $sym);
  1557.                   eval '@foo = ()' if defined(@foo);
  1558.                   die "No XYZ package defined" unless defined %_XYZ;
  1559.                   sub foo { defined &$bar ? &$bar(@_) : die "No bar"; }
  1560.  
  1561.              See also undef.
  1562.  
  1563.      delete $ASSOC{KEY}
  1564.              Deletes the specified value from the specified asso-
  1565.              ciative  array.   Returns  the deleted value, or the
  1566.              undefined value if nothing  was  deleted.   Deleting
  1567.              from $ENV{} modifies the environment.  Deleting from
  1568.              an array bound to a dbm file deletes the entry  from
  1569.              the dbm file.
  1570.  
  1571.              The following deletes all the values of an  associa-
  1572.              tive array:
  1573.  
  1574.                   foreach $key (keys %ARRAY) {
  1575.                        delete $ARRAY{$key};
  1576.                   }
  1577.  
  1578.              (But it would be faster to use  the  reset  command.
  1579.              Saying undef %ARRAY is faster yet.)
  1580.  
  1581.      die(LIST)
  1582.      die LIST
  1583.              Outside of an eval, prints  the  value  of  LIST  to
  1584.              STDERR  and  exits  with  the  current  value  of $!
  1585.              (errno).  If $! is 0, exits with the value of ($? >>
  1586.              8)  (`command`  status).   If  ($? >> 8) is 0, exits
  1587.              with 255.  Inside an  eval,  the  error  message  is
  1588.              stuffed  into $@ and the eval is terminated with the
  1589.              undefined value.
  1590.  
  1591.              Equivalent examples:
  1592.  
  1593.                   die "Can't cd to spool: $!\n"
  1594.                        unless chdir '/usr/spool/news';
  1595.  
  1596.                   chdir '/usr/spool/news' || die "Can't cd to spool: $!\n"
  1597.  
  1598.              If the value of EXPR does not end in a newline,  the
  1599.              current script line number and input line number (if
  1600.              any) are also printed, and a  newline  is  supplied.
  1601.              Hint:  sometimes  appending ", stopped" to your mes-
  1602.              sage will cause it to make  better  sense  when  the
  1603.              string  "at  foo line 123" is appended.  Suppose you
  1604.              are running script "canasta".
  1605.  
  1606.                   die "/etc/games is no good";
  1607.                   die "/etc/games is no good, stopped";
  1608.  
  1609.              produce, respectively
  1610.  
  1611.                   /etc/games is no good at canasta line 123.
  1612.                   /etc/games is no good, stopped at canasta line 123.
  1613.  
  1614.              See also exit.
  1615.  
  1616.      do BLOCK
  1617.              Returns  the  value  of  the  last  command  in  the
  1618.              sequence of commands indicated by BLOCK.  When modi-
  1619.              fied by a loop modifier,  executes  the  BLOCK  once
  1620.              before testing the loop condition.  (On other state-
  1621.              ments  the  loop  modifiers  test  the   conditional
  1622.              first.)
  1623.  
  1624.      do SUBROUTINE (LIST)
  1625.              Executes a SUBROUTINE declared by a sub declaration,
  1626.              and   returns  the  value  of  the  last  expression
  1627.              evaluated in SUBROUTINE.  If there is no  subroutine
  1628.              by  that name, produces a fatal error.  (You may use
  1629.              the "defined" operator to determine if a  subroutine
  1630.              exists.)  If you pass arrays as part of LIST you may
  1631.              wish to pass the length of the  array  in  front  of
  1632.              each  array.   (See the section on Subroutines later
  1633.              on.) The parentheses are required to avoid confusion
  1634.              with the "do EXPR" form.
  1635.  
  1636.              SUBROUTINE may also be a single scalar variable,  in
  1637.              which  case the name of the subroutine to execute is
  1638.              taken from the variable.
  1639.  
  1640.              As an alternate (and preferred) form, you may call a
  1641.              subroutine  by prefixing the name with an ampersand:
  1642.              &foo(@args).  If you aren't passing  any  arguments,
  1643.              you  don't have to use parentheses.  If you omit the
  1644.              parentheses, no @_ array is passed  to  the  subrou-
  1645.              tine.   The  &  form is also used to specify subrou-
  1646.              tines to the defined and undef operators:
  1647.  
  1648.                   if (defined &$var) { &$var($parm); undef &$var; }
  1649.  
  1650.      do EXPR Uses the value of EXPR as a  filename  and  executes
  1651.              the contents of the file as a perl script.  Its pri-
  1652.              mary use is to include subroutines from a perl  sub-
  1653.              routine library.
  1654.  
  1655.                   do 'stat.pl';
  1656.  
  1657.              is just like
  1658.  
  1659.                   eval `cat stat.pl`;
  1660.  
  1661.              except that it's more efficient, more concise, keeps
  1662.              track  of  the  current filename for error messages,
  1663.              and searches all the -I libraries if the file  isn't
  1664.              in the current directory (see also the @INC array in
  1665.              Predefined Names).  It's the same, however, in  that
  1666.              it  does reparse the file every time you call it, so
  1667.              if you are going to use the file inside a  loop  you
  1668.              might  prefer to use -P and #include, at the expense
  1669.              of a little more startup time.   (The  main  problem
  1670.              with #include is that cpp doesn't grok # comments--a
  1671.              workaround is to use ";#" for standalone  comments.)
  1672.              Note that the following are NOT equivalent:
  1673.  
  1674.                   do $foo;  # eval a file
  1675.                   do $foo();     # call a subroutine
  1676.  
  1677.              Note that inclusion of library  routines  is  better
  1678.              done with the "require" operator.
  1679.  
  1680.      dump LABEL
  1681.              This causes an immediate core dump.  Primarily  this
  1682.              is  so  that  you can use the undump program to turn
  1683.              your core dump into an executable binary after  hav-
  1684.              ing  initialized all your variables at the beginning
  1685.              of the program.  When the new binary is executed  it
  1686.              will begin by executing a "goto LABEL" (with all the
  1687.              restrictions that goto suffers).  Think of it  as  a
  1688.              goto  with  an  intervening core dump and reincarna-
  1689.              tion.  If LABEL is  omitted,  restarts  the  program
  1690.              from the top.  WARNING: any files opened at the time
  1691.              of the dump will NOT be open any more when the  pro-
  1692.              gram is reincarnated, with possible resulting confu-
  1693.              sion on the part of perl.  See also -u.
  1694.  
  1695.              Example:
  1696.  
  1697.                   #!/usr/bin/perl
  1698.                   require 'getopt.pl';
  1699.                   require 'stat.pl';
  1700.                   %days = (
  1701.                       'Sun',1,
  1702.                       'Mon',2,
  1703.                       'Tue',3,
  1704.                       'Wed',4,
  1705.                       'Thu',5,
  1706.                       'Fri',6,
  1707.                       'Sat',7);
  1708.  
  1709.                   dump QUICKSTART if $ARGV[0] eq '-d';
  1710.  
  1711.                  QUICKSTART:
  1712.                   do Getopt('f');
  1713.  
  1714.      each(ASSOC_ARRAY)
  1715.      each ASSOC_ARRAY
  1716.              Returns a 2 element array consisting of the key  and
  1717.              value for the next value of an associative array, so
  1718.              that you can iterate over it.  Entries are  returned
  1719.              in  an  apparently  random order.  When the array is
  1720.              entirely read, a null array is returned (which  when
  1721.              assigned produces a FALSE (0) value).  The next call
  1722.              to each() after that  will  start  iterating  again.
  1723.              The  iterator  can  be reset only by reading all the
  1724.              elements from the array.  You must  not  modify  the
  1725.              array  while  iterating  over it.  There is a single
  1726.              iterator for each associative array, shared  by  all
  1727.              each(),  keys()  and  values() function calls in the
  1728.              program.  The following prints out your  environment
  1729.              like  the  printenv  program,  only  in  a different
  1730.              order:
  1731.  
  1732.                   while (($key,$value) = each %ENV) {
  1733.                        print "$key=$value\n";
  1734.                   }
  1735.  
  1736.              See also keys() and values().
  1737.  
  1738.      eof(FILEHANDLE)
  1739.      eof()
  1740.      eof     Returns 1 if the next read on FILEHANDLE will return
  1741.              end of file, or if FILEHANDLE is not open.  FILEHAN-
  1742.              DLE may be an expression whose value gives the  real
  1743.              filehandle  name.  (Note that this function actually
  1744.              reads a character and then ungetc's it, so it is not
  1745.              very  useful  in  an  interactive  context.)  An eof
  1746.              without an argument returns the eof status  for  the
  1747.              last file read.  Empty parentheses () may be used to
  1748.              indicate the pseudo file formed of the files  listed
  1749.              on the command line, i.e. eof() is reasonable to use
  1750.              inside a while (<>) loop to detect the end  of  only
  1751.              the  last  file.   Use  eof(ARGV) or eof without the
  1752.              parentheses to test EACH file in a while (<>)  loop.
  1753.              Examples:
  1754.  
  1755.                   # insert dashes just before last line of last file
  1756.                   while (<>) {
  1757.                        if (eof()) {
  1758.                             print "--------------\n";
  1759.                        }
  1760.                        print;
  1761.                   }
  1762.  
  1763.                   # reset line numbering on each input file
  1764.                   while (<>) {
  1765.                        print "$.\t$_";
  1766.                        if (eof) {     # Not eof().
  1767.                             close(ARGV);
  1768.                        }
  1769.                   }
  1770.  
  1771.      eval(EXPR)
  1772.      eval EXPR
  1773.      eval BLOCK
  1774.              EXPR is parsed and executed as if it were  a  little
  1775.              perl  program.  It is executed in the context of the
  1776.              current perl program, so that any variable settings,
  1777.              subroutine  or format definitions remain afterwards.
  1778.              The value returned is the value of the last  expres-
  1779.              sion  evaluated, just as with subroutines.  If there
  1780.              is a syntax error or runtime error, or a die  state-
  1781.              ment  is executed, an undefined value is returned by
  1782.              eval, and $@ is set to the error message.  If  there
  1783.              was  no error, $@ is guaranteed to be a null string.
  1784.              If EXPR is omitted, evaluates $_.  The  final  semi-
  1785.              colon, if any, may be omitted from the expression.
  1786.  
  1787.              Note that, since eval traps otherwise-fatal  errors,
  1788.              it  is  useful  for determining whether a particular
  1789.              feature (such as dbmopen or symlink) is implemented.
  1790.              It  is  also  Perl's  exception  trapping mechanism,
  1791.              where the die operator is used to raise exceptions.
  1792.  
  1793.              If the code to be executed doesn't vary, you may use
  1794.              the  eval-BLOCK form to trap run-time errors without
  1795.              incurring the penalty of recompiling each time.  The
  1796.              error,  if any, is still returned in $@.  Evaluating
  1797.              a  single-quoted  string  (as  EXPR)  has  the  same
  1798.              effect,  except that the eval-EXPR form reports syn-
  1799.              tax errors at run time via  $@,  whereas  the  eval-
  1800.              BLOCK  form  reports  syntax errors at compile time.
  1801.              The eval-EXPR form is optimized  to  eval-BLOCK  the
  1802.              first time it succeeds.  (Since the replacement side
  1803.              of a  substitution  is  considered  a  single-quoted
  1804.              string when you use the e modifier, the same optimi-
  1805.              zation occurs there.)  Examples:
  1806.  
  1807.                   # make divide-by-zero non-fatal
  1808.                   eval { $answer = $a / $b; }; warn $@ if $@;
  1809.  
  1810.                   # optimized to same thing after first use
  1811.                   eval '$answer = $a / $b'; warn $@ if $@;
  1812.  
  1813.                   # a compile-time error
  1814.                   eval { $answer = };
  1815.  
  1816.                   # a run-time error
  1817.                   eval '$answer =';   # sets $@
  1818.  
  1819.      exec(LIST)
  1820.      exec LIST
  1821.              If there is more than one argument in  LIST,  or  if
  1822.              LIST  is  an  array  with more than one value, calls
  1823.              execvp() with the arguments in LIST.   If  there  is
  1824.              only  one  scalar  argument, the argument is checked
  1825.              for shell metacharacters.  If  there  are  any,  the
  1826.              entire  argument is passed to "/bin/sh -c" for pars-
  1827.              ing.  If there are none, the argument is split  into
  1828.              words and passed directly to execvp(), which is more
  1829.              efficient.  Note: exec (and  system)  do  not  flush
  1830.              your  output  buffer,  so  you may need to set $| to
  1831.              avoid lost output.  Examples:
  1832.  
  1833.                   exec '/bin/echo', 'Your arguments are: ', @ARGV;
  1834.                   exec "sort $outfile | uniq";
  1835.  
  1836.              If you don't really want to execute the first  argu-
  1837.              ment, but want to lie to the program you are execut-
  1838.              ing about its own name, you can specify the  program
  1839.              you  actually  want  to  run  by assigning that to a
  1840.              variable and putting the name  of  the  variable  in
  1841.              front  of  the  LIST  without a comma.  (This always
  1842.              forces interpretation of the LIST as a  multi-valued
  1843.              list,  even  if there is only a single scalar in the
  1844.              list.) Example:
  1845.  
  1846.                   $shell = '/bin/csh';
  1847.                   exec $shell '-sh';       # pretend it's a login shell
  1848.  
  1849.      exit EXPR
  1850.              Evaluates  EXPR  and  exits  immediately  with  that
  1851.              value.  Example:
  1852.  
  1853.                   $ans = <STDIN>;
  1854.                   exit 0 if $ans =~ /^[Xx]/;
  1855.  
  1856.              See also die.  If EXPR  is  omitted,  exits  with  0
  1857.              status.
  1858.  
  1859.      exp(EXPR)
  1860.      exp EXPR
  1861.              Returns e to the power of EXPR.  If EXPR is omitted,
  1862.              gives exp($_).
  1863.  
  1864.      fcntl(FILEHANDLE,FUNCTION,SCALAR)
  1865.              Implements the fcntl(2) function.   You'll  probably
  1866.              have to say
  1867.  
  1868.                   require "fcntl.ph"; # probably /usr/local/lib/perl/fcntl.ph
  1869.  
  1870.              first to get the correct function  definitions.   If
  1871.              fcntl.ph  doesn't  exist or doesn't have the correct
  1872.              definitions you'll have to roll your own,  based  on
  1873.              your  C  header files such as <sys/fcntl.h>.  (There
  1874.              is a perl script called h2ph  that  comes  with  the
  1875.              perl  kit which may help you in this.) Argument pro-
  1876.              cessing and  value  return  works  just  like  ioctl
  1877.              below.   Note  that fcntl will produce a fatal error
  1878.              if  used  on  a  machine  that   doesn't   implement
  1879.              fcntl(2).
  1880.  
  1881.      fileno(FILEHANDLE)
  1882.      fileno FILEHANDLE
  1883.              Returns the file descriptor for a filehandle.   Use-
  1884.              ful  for  constructing  bitmaps  for  select().   If
  1885.              FILEHANDLE is an expression, the value is  taken  as
  1886.              the name of the filehandle.
  1887.  
  1888.      flock(FILEHANDLE,OPERATION)
  1889.              Calls flock(2) on FILEHANDLE.  See manual  page  for
  1890.              flock(2)  for definition of OPERATION.  Returns true
  1891.              for success, false on failure.  Will produce a fatal
  1892.              error  if  used  on a machine that doesn't implement
  1893.              flock(2).  Here's a mailbox appender  for  BSD  sys-
  1894.              tems.
  1895.  
  1896.                   $LOCK_SH = 1;
  1897.                   $LOCK_EX = 2;
  1898.                   $LOCK_NB = 4;
  1899.                   $LOCK_UN = 8;
  1900.  
  1901.                   sub lock {
  1902.                       flock(MBOX,$LOCK_EX);
  1903.                       # and, in case someone appended
  1904.                       # while we were waiting...
  1905.                       seek(MBOX, 0, 2);
  1906.                   }
  1907.  
  1908.                   sub unlock {
  1909.                       flock(MBOX,$LOCK_UN);
  1910.                   }
  1911.  
  1912.                   open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
  1913.                        || die "Can't open mailbox: $!";
  1914.  
  1915.                   do lock();
  1916.                   print MBOX $msg,"\n\n";
  1917.                   do unlock();
  1918.  
  1919.      fork    Does a fork() call.  Returns the child  pid  to  the
  1920.              parent  process  and  0 to the child process.  Note:
  1921.              unflushed   buffers   remain   unflushed   in   both
  1922.              processes,  which  means  you  may need to set $| to
  1923.              avoid duplicate output.
  1924.  
  1925.      getc(FILEHANDLE)
  1926.      getc FILEHANDLE
  1927.      getc    Returns the  next  character  from  the  input  file
  1928.              attached to FILEHANDLE, or a null string at EOF.  If
  1929.              FILEHANDLE is omitted, reads from STDIN.
  1930.  
  1931.      getlogin
  1932.              Returns the current login from  /etc/utmp,  if  any.
  1933.              If null, use getpwuid.
  1934.  
  1935.                   $login  =  getlogin  ||  (getpwuid($<))[0]   ||
  1936.              "Somebody";
  1937.  
  1938.      getpeername(SOCKET)
  1939.              Returns the packed sockaddr address of other end  of
  1940.              the SOCKET connection.
  1941.  
  1942.                   # An internet sockaddr
  1943.                   $sockaddr = 'S n a4 x8';
  1944.                   $hersockaddr = getpeername(S);
  1945.                   ($family, $port, $heraddr) =
  1946.                             unpack($sockaddr,$hersockaddr);
  1947.  
  1948.      getpgrp(PID)
  1949.      getpgrp PID
  1950.              Returns the current process group for the  specified
  1951.              PID,  0  for  the  current  process.  Will produce a
  1952.              fatal error if used on a machine that doesn't imple-
  1953.              ment  getpgrp(2).   If EXPR is omitted, returns pro-
  1954.              cess group of current process.
  1955.  
  1956.      getppid Returns the process id of the parent process.
  1957.  
  1958.      getpriority(WHICH,WHO)
  1959.              Returns the current priority for a process,  a  pro-
  1960.              cess  group,  or a user.  (See getpriority(2).) Will
  1961.              produce a fatal error if  used  on  a  machine  that
  1962.              doesn't implement getpriority(2).
  1963.  
  1964.      getgrnam(NAME)
  1965.      gethostbyname(NAME)
  1966.      getnetbyname(NAME)
  1967.      getprotobyname(NAME)
  1968.      getpwuid(UID)
  1969.      getgrgid(GID)
  1970.      getservbyname(NAME,PROTO)
  1971.      gethostbyaddr(ADDR,ADDRTYPE)
  1972.      getnetbyaddr(ADDR,ADDRTYPE)
  1973.      getprotobynumber(NUMBER)
  1974.      getservbyport(PORT,PROTO)
  1975.      getpwent
  1976.      getgrent
  1977.      gethostent
  1978.      getnetent
  1979.      getprotoent
  1980.      getservent
  1981.      setpwent
  1982.      setgrent
  1983.      sethostent(STAYOPEN)
  1984.      setnetent(STAYOPEN)
  1985.      setprotoent(STAYOPEN)
  1986.      setservent(STAYOPEN)
  1987.      endpwent
  1988.      endgrent
  1989.      endhostent
  1990.      endnetent
  1991.      endprotoent
  1992.      endservent
  1993.              These routines perform the same functions  as  their
  1994.              counterparts  in  the  system  library.   The return
  1995.              values from the various get routines are as follows:
  1996.  
  1997.                   ($name,$passwd,$uid,$gid,
  1998.                      $quota,$comment,$gcos,$dir,$shell) = getpw...
  1999.                   ($name,$passwd,$gid,$members) = getgr...
  2000.                   ($name,$aliases,$addrtype,$length,@addrs) = gethost...
  2001.                   ($name,$aliases,$addrtype,$net) = getnet...
  2002.                   ($name,$aliases,$proto) = getproto...
  2003.                   ($name,$aliases,$port,$proto) = getserv...
  2004.  
  2005.              The $members value returned by getgr... is  a  space
  2006.              separated  list of the login names of the members of
  2007.              the group.
  2008.  
  2009.              The @addrs value returned by  the  gethost...  func-
  2010.              tions is a list of the raw addresses returned by the
  2011.              corresponding system library call.  In the  Internet
  2012.              domain,  each address is four bytes long and you can
  2013.              unpack it by saying something like:
  2014.  
  2015.                   ($a,$b,$c,$d) = unpack('C4',$addr[0]);
  2016.  
  2017.      getsockname(SOCKET)
  2018.              Returns the packed sockaddr address of this  end  of
  2019.              the SOCKET connection.
  2020.  
  2021.                   # An internet sockaddr
  2022.                   $sockaddr = 'S n a4 x8';
  2023.                   $mysockaddr = getsockname(S);
  2024.                   ($family, $port, $myaddr) =
  2025.                             unpack($sockaddr,$mysockaddr);
  2026.  
  2027.      getsockopt(SOCKET,LEVEL,OPTNAME)
  2028.              Returns the socket option requested, or undefined if
  2029.              there is an error.
  2030.  
  2031.      gmtime(EXPR)
  2032.      gmtime EXPR
  2033.              Converts a time as returned by the time function  to
  2034.              a  9-element  array  with  the time analyzed for the
  2035.              Greenwich timezone.  Typically used as follows:
  2036.  
  2037.              ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  2038.                                            gmtime(time);
  2039.  
  2040.              All array elements are numeric,  and  come  straight
  2041.              out  of  a struct tm.  In particular this means that
  2042.              $mon has the range 0..11 and  $wday  has  the  range
  2043.              0..6.  If EXPR is omitted, does gmtime(time).
  2044.  
  2045.      goto LABEL
  2046.              Finds the statement labeled with LABEL  and  resumes
  2047.              execution  there.   Currently  you  may  only  go to
  2048.              statements in the main body of the program that  are
  2049.              not nested inside a do {} construct.  This statement
  2050.              is not implemented very  efficiently,  and  is  here
  2051.              only  to  make the sed-to-perl translator easier.  I
  2052.              may change its semantics  at  any  time,  consistent
  2053.              with  support for translated sed scripts.  Use it at
  2054.              your own risk.  Better yet, don't use it at all.
  2055.  
  2056.      grep(EXPR,LIST)
  2057.              Evaluates EXPR for each  element  of  LIST  (locally
  2058.              setting  $_  to  each element) and returns the array
  2059.              value consisting of those  elements  for  which  the
  2060.              expression  evaluated to true.  In a scalar context,
  2061.              returns the number of times the expression was true.
  2062.  
  2063.                   @foo = grep(!/^#/, @bar);    # weed out comments
  2064.  
  2065.              Note that, since $_ is a reference  into  the  array
  2066.              value,  it can be used to modify the elements of the
  2067.              array.  While this is useful and supported,  it  can
  2068.              cause  bizarre  results  if  the LIST is not a named
  2069.              array.
  2070.  
  2071.      hex(EXPR)
  2072.      hex EXPR
  2073.              Returns the decimal value of EXPR interpreted as  an
  2074.              hex  string.  (To interpret strings that might start
  2075.              with 0 or 0x see oct().) If EXPR  is  omitted,  uses
  2076.              $_.
  2077.  
  2078.      index(STR,SUBSTR,POSITION)
  2079.      index(STR,SUBSTR)
  2080.              Returns the position  of  the  first  occurrence  of
  2081.              SUBSTR  in STR at or after POSITION.  If POSITION is
  2082.              omitted, starts searching from the beginning of  the
  2083.              string.  The return value is based at 0, or whatever
  2084.              you've set the $[ variable to.  If the substring  is
  2085.              not  found,  returns  one  less than the base, ordi-
  2086.              narily -1.
  2087.  
  2088.      int(EXPR)
  2089.      int EXPR
  2090.              Returns the integer portion of  EXPR.   If  EXPR  is
  2091.              omitted, uses $_.
  2092.  
  2093.      ioctl(FILEHANDLE,FUNCTION,SCALAR)
  2094.              Implements the ioctl(2) function.   You'll  probably
  2095.              have to say
  2096.  
  2097.                   require "ioctl.ph"; # probably /usr/local/lib/perl/ioctl.ph
  2098.  
  2099.              first to get the correct function  definitions.   If
  2100.              ioctl.ph  doesn't  exist or doesn't have the correct
  2101.              definitions you'll have to roll your own,  based  on
  2102.              your  C  header files such as <sys/ioctl.h>.  (There
  2103.              is a perl script called h2ph  that  comes  with  the
  2104.              perl kit which may help you in this.) SCALAR will be
  2105.              read and/or written  depending  on  the  FUNCTION--a
  2106.              pointer to the string value of SCALAR will be passed
  2107.              as the third argument of the actual ioctl call.  (If
  2108.              SCALAR  has  no string value but does have a numeric
  2109.              value, that value  will  be  passed  rather  than  a
  2110.              pointer  to  the string value.  To guarantee this to
  2111.              be true, add a 0 to the scalar before using it.) The
  2112.              pack() and unpack() functions are useful for manipu-
  2113.              lating the values of  structures  used  by  ioctl().
  2114.  
  2115.              The  following  example  sets the erase character to
  2116.              DEL.
  2117.  
  2118.                   require 'ioctl.ph';
  2119.                   $sgttyb_t = "ccccs";          # 4 chars and a short
  2120.                   if (ioctl(STDIN,$TIOCGETP,$sgttyb)) {
  2121.                        @ary = unpack($sgttyb_t,$sgttyb);
  2122.                        $ary[2] = 127;
  2123.                        $sgttyb = pack($sgttyb_t,@ary);
  2124.                        ioctl(STDIN,$TIOCSETP,$sgttyb)
  2125.                             || die "Can't ioctl: $!";
  2126.                   }
  2127.  
  2128.              The return value of ioctl (and fcntl) is as follows:
  2129.  
  2130.                   if OS returns:           perl returns:
  2131.                     -1                       undefined value
  2132.                     0                        string "0 but true"
  2133.                     anything else            that number
  2134.  
  2135.              Thus perl returns  true  on  success  and  false  on
  2136.              failure,  yet  you  can  still  easily determine the
  2137.              actual value returned by the operating system:
  2138.  
  2139.                   ($retval = ioctl(...)) || ($retval = -1);
  2140.                   printf "System returned %d\n", $retval;
  2141.  
  2142.      join(EXPR,LIST)
  2143.      join(EXPR,ARRAY)
  2144.              Joins the separate strings of LIST or ARRAY  into  a
  2145.              single  string with fields separated by the value of
  2146.              EXPR, and returns the string.  Example:
  2147.  
  2148.              $_ = join(':',
  2149.                        $login,$passwd,$uid,$gid,$gcos,$home,$shell);
  2150.  
  2151.              See split.
  2152.  
  2153.      keys(ASSOC_ARRAY)
  2154.      keys ASSOC_ARRAY
  2155.              Returns a normal array consisting of all the keys of
  2156.              the  named associative array.  The keys are returned
  2157.              in an apparently random order, but it  is  the  same
  2158.              order as either the values() or each() function pro-
  2159.              duces (given that the associative array has not been
  2160.              modified).   Here  is  yet another way to print your
  2161.              environment:
  2162.  
  2163.                   @keys = keys %ENV;
  2164.                   @values = values %ENV;
  2165.                   while ($#keys >= 0) {
  2166.                        print pop(@keys), '=', pop(@values), "\n";
  2167.                   }
  2168.  
  2169.              or how about sorted by key:
  2170.  
  2171.                   foreach $key (sort(keys %ENV)) {
  2172.                        print $key, '=', $ENV{$key}, "\n";
  2173.                   }
  2174.  
  2175.      kill(LIST)
  2176.      kill LIST
  2177.              Sends a signal to a list of  processes.   The  first
  2178.              element  of  the  list  must  be the signal to send.
  2179.              Returns the number of  processes  successfully  sig-
  2180.              naled.
  2181.  
  2182.                   $cnt = kill 1, $child1, $child2;
  2183.                   kill 9, @goners;
  2184.  
  2185.              If the signal  is  negative,  kills  process  groups
  2186.              instead of processes.  (On System V, a negative pro-
  2187.              cess number  will  also  kill  process  groups,  but
  2188.              that's  not  portable.) You may use a signal name in
  2189.              quotes.
  2190.  
  2191.      last LABEL
  2192.      last    The last command is like the break  statement  in  C
  2193.              (as used in loops); it immediately exits the loop in
  2194.              question.  If the  LABEL  is  omitted,  the  command
  2195.              refers  to  the  innermost enclosing loop.  The con-
  2196.              tinue block, if any, is not executed:
  2197.  
  2198.                   line: while (<STDIN>) {
  2199.                        last line if /^$/;  # exit when done with header
  2200.                        ...
  2201.                   }
  2202.  
  2203.      length(EXPR)
  2204.      length EXPR
  2205.              Returns the length in characters  of  the  value  of
  2206.              EXPR.  If EXPR is omitted, returns length of $_.
  2207.  
  2208.      link(OLDFILE,NEWFILE)
  2209.              Creates a new filename linked to the  old  filename.
  2210.  
  2211.              Returns 1 for success, 0 otherwise.
  2212.  
  2213.      listen(SOCKET,QUEUESIZE)
  2214.              Does the same thing  that  the  listen  system  call
  2215.              does.   Returns  true  if it succeeded, false other-
  2216.              wise.  See example in section on  Interprocess  Com-
  2217.              munication.
  2218.  
  2219.      local(LIST)
  2220.              Declares the listed variables to  be  local  to  the
  2221.              enclosing  block, subroutine, eval or "do".  All the
  2222.              listed elements must be legal lvalues.  This  opera-
  2223.              tor  works  by  saving  the  current values of those
  2224.              variables in LIST on a hidden  stack  and  restoring
  2225.              them  upon  exiting  the  block, subroutine or eval.
  2226.              This means that called subroutines can  also  refer-
  2227.              ence  the  local  variable,  but not the global one.
  2228.              The LIST may be assigned to if desired, which allows
  2229.              you to initialize your local variables.  (If no ini-
  2230.              tializer is given for a particular variable,  it  is
  2231.              created  with  an undefined value.) Commonly this is
  2232.              used to name the parameters to a subroutine.   Exam-
  2233.              ples:
  2234.  
  2235.                   sub RANGEVAL {
  2236.                        local($min, $max, $thunk) = @_;
  2237.                        local($result) = '';
  2238.                        local($i);
  2239.  
  2240.                        # Presumably $thunk makes reference to $i
  2241.  
  2242.                        for ($i = $min; $i < $max; $i++) {
  2243.                             $result .= eval $thunk;
  2244.                        }
  2245.  
  2246.                        $result;
  2247.                   }
  2248.  
  2249.                   if ($sw eq '-v') {
  2250.                       # init local array with global array
  2251.                       local(@ARGV) = @ARGV;
  2252.                       unshift(@ARGV,'echo');
  2253.                       system @ARGV;
  2254.                   }
  2255.                   # @ARGV restored
  2256.  
  2257.                   # temporarily add to digits associative array
  2258.                   if ($base12) {
  2259.                        # (NOTE: not claiming this is efficient!)
  2260.                        local(%digits) = (%digits,'t',10,'e',11);
  2261.                        do parse_num();
  2262.                   }
  2263.  
  2264.              Note that local() is a run-time command, and so gets
  2265.              executed  every  time  through a loop, using up more
  2266.              stack storage each time until it's all  released  at
  2267.              once when the loop is exited.
  2268.  
  2269.      localtime(EXPR)
  2270.      localtime EXPR
  2271.              Converts a time as returned by the time function  to
  2272.              a  9-element  array  with  the time analyzed for the
  2273.              local timezone.  Typically used as follows:
  2274.  
  2275.              ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  2276.                                            localtime(time);
  2277.  
  2278.              All array elements are numeric,  and  come  straight
  2279.              out  of  a struct tm.  In particular this means that
  2280.              $mon has the range 0..11 and  $wday  has  the  range
  2281.              0..6.  If EXPR is omitted, does localtime(time).
  2282.  
  2283.      log(EXPR)
  2284.      log EXPR
  2285.              Returns logarithm (base e)  of  EXPR.   If  EXPR  is
  2286.              omitted, returns log of $_.
  2287.  
  2288.      lstat(FILEHANDLE)
  2289.      lstat FILEHANDLE
  2290.      lstat(EXPR)
  2291.      lstat SCALARVARIABLE
  2292.              Does the same thing  as  the  stat()  function,  but
  2293.              stats  a  symbolic link instead of the file the sym-
  2294.              bolic link points to.  If symbolic links  are  unim-
  2295.              plemented on your system, a normal stat is done.
  2296.  
  2297.      m/PATTERN/gio
  2298.      /PATTERN/gio
  2299.              Searches a string for a pattern match,  and  returns
  2300.              true  (1)  or false ('').  If no string is specified
  2301.              via  the  =~  or  !~  operator,  the  $_  string  is
  2302.              searched.  (The string specified with =~ need not be
  2303.              an lvalue--it may be the  result  of  an  expression
  2304.              evaluation,   but   remember  the  =~  binds  rather
  2305.              tightly.) See also the section  on  Regular  Expres-
  2306.              sions.
  2307.  
  2308.              If / is  the  delimiter  then  the  initial  'm'  is
  2309.              optional.   With  the  'm'  you  can use any pair of
  2310.              non-alphanumeric characters as delimiters.  This  is
  2311.              particularly  useful  for  matching  Unix path names
  2312.              that contain '/'.  If the final  delimiter  is  fol-
  2313.              lowed  by  the  optional letter 'i', the matching is
  2314.              done in a case-insensitive manner.  PATTERN may con-
  2315.              tain  references  to scalar variables, which will be
  2316.              interpolated (and the pattern recompiled) every time
  2317.              the  pattern search is evaluated.  (Note that $) and
  2318.              $| may not be interpolated because  they  look  like
  2319.              end-of-string  tests.) If you want such a pattern to
  2320.              be compiled only once, add an "o" after the trailing
  2321.              delimiter.   This avoids expensive run-time recompi-
  2322.              lations, and is useful when the value you are inter-
  2323.              polating  won't  change over the life of the script.
  2324.              If the PATTERN evaluates to a null string, the  most
  2325.              recent   successful   regular   expression  is  used
  2326.              instead.
  2327.  
  2328.              If used in a context that requires an array value, a
  2329.              pattern  match  returns  an  array consisting of the
  2330.              subexpressions matched by  the  parentheses  in  the
  2331.              pattern, i.e. ($1, $2, $3...).  It does NOT actually
  2332.              set $1, $2, etc. in this case, nor does it  set  $+,
  2333.              $`,  $&  or $'.  If the match fails, a null array is
  2334.              returned.  If the match succeeds, but there were  no
  2335.              parentheses, an array value of (1) is returned.
  2336.  
  2337.              Examples:
  2338.  
  2339.                  open(tty, '/dev/tty');
  2340.                  <tty> =~ /^y/i && do foo();    # do foo if desired
  2341.  
  2342.                  if (/Version: *([0-9.]*)/) { $version = $1; }
  2343.  
  2344.                  next if m#^/usr/spool/uucp#;
  2345.  
  2346.                  # poor man's grep
  2347.                  $arg = shift;
  2348.                  while (<>) {
  2349.                       print if /$arg/o;    # compile only once
  2350.                  }
  2351.  
  2352.                  if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
  2353.  
  2354.              This last example splits $foo  into  the  first  two
  2355.              words  and  the  remainder  of the line, and assigns
  2356.              those three fields to $F1, $F2 and $Etc.  The condi-
  2357.              tional  is true if any variables were assigned, i.e.
  2358.              if the pattern matched.
  2359.  
  2360.              The   "g"   modifier   specifies   global    pattern
  2361.              matching--that   is,   matching  as  many  times  as
  2362.              possible within the string.  How it behaves  depends
  2363.              on  the  context.  In an array context, it returns a
  2364.              list of  all  the  substrings  matched  by  all  the
  2365.              parentheses in the regular expression.  If there are
  2366.              no parentheses, it returns a list of all the matched
  2367.              strings,  as  if  there  were parentheses around the
  2368.              whole pattern.  In a  scalar  context,  it  iterates
  2369.              through  the  string,  returning  TRUE  each time it
  2370.              matches, and FALSE when it eventually  runs  out  of
  2371.              matches.   (In  other  words,  it remembers where it
  2372.              left off last time and restarts the search  at  that
  2373.              point.)   It presumes that you have not modified the
  2374.              string since the last match.  Modifying  the  string
  2375.              between  matches  may  result in undefined behavior.
  2376.              (You can actually get away with  in-place  modifica-
  2377.              tions  via substr() that do not change the length of
  2378.              the entire string.  In general, however, you  should
  2379.              be using s///g for such modifications.)  Examples:
  2380.  
  2381.                   # array context
  2382.                   ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);
  2383.  
  2384.                   # scalar context
  2385.                   $/ = 1; $* = 1;
  2386.                   while ($paragraph = <>) {
  2387.                       while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
  2388.                        $sentences++;
  2389.                       }
  2390.                   }
  2391.                   print "$sentences\n";
  2392.  
  2393.      mkdir(FILENAME,MODE)
  2394.              Creates the directory specified  by  FILENAME,  with
  2395.              permissions   specified  by  MODE  (as  modified  by
  2396.              umask).  If it succeeds it returns 1,  otherwise  it
  2397.              returns 0 and sets $! (errno).
  2398.  
  2399.      msgctl(ID,CMD,ARG)
  2400.              Calls the System V IPC function msgctl.  If  CMD  is
  2401.              &IPC_STAT,  then  ARG  must be a variable which will
  2402.              hold the returned msqid_ds structure.  Returns  like
  2403.              ioctl:  the  undefined value for error, "0 but true"
  2404.              for zero, or the actual return value otherwise.
  2405.  
  2406.      msgget(KEY,FLAGS)
  2407.              Calls the System V IPC function msgget.  Returns the
  2408.              message queue id, or the undefined value if there is
  2409.              an error.
  2410.  
  2411.      msgsnd(ID,MSG,FLAGS)
  2412.              Calls the System V IPC function msgsnd to  send  the
  2413.              message MSG to the message queue ID.  MSG must begin
  2414.              with the long integer message  type,  which  may  be
  2415.              created with pack("L", $type).  Returns true if suc-
  2416.              cessful, or false if there is an error.
  2417.  
  2418.      msgrcv(ID,VAR,SIZE,TYPE,FLAGS)
  2419.              Calls the System V IPC function msgrcv to receive  a
  2420.              message from message queue ID into variable VAR with
  2421.              a maximum message size of SIZE.  Note that if a mes-
  2422.              sage is received, the message type will be the first
  2423.              thing in VAR, and the maximum length of VAR is  SIZE
  2424.              plus  the size of the message type.  Returns true if
  2425.              successful, or false if there is an error.
  2426.  
  2427.      next LABEL
  2428.      next    The next command is like the continue  statement  in
  2429.              C; it starts the next iteration of the loop:
  2430.  
  2431.                   line: while (<STDIN>) {
  2432.                        next line if /^#/;  # discard comments
  2433.                        ...
  2434.                   }
  2435.  
  2436.              Note that if there were  a  continue  block  on  the
  2437.              above,  it  would  get  executed  even  on discarded
  2438.              lines.  If the LABEL is omitted, the command  refers
  2439.              to the innermost enclosing loop.
  2440.  
  2441.      oct(EXPR)
  2442.      oct EXPR
  2443.              Returns the decimal value of EXPR interpreted as  an
  2444.              octal  string.   (If  EXPR happens to start off with
  2445.              0x, interprets it as a hex string instead.) The fol-
  2446.              lowing  will  handle  decimal,  octal and hex in the
  2447.              standard notation:
  2448.  
  2449.                   $val = oct($val) if $val =~ /^0/;
  2450.  
  2451.              If EXPR is omitted, uses $_.
  2452.  
  2453.      open(FILEHANDLE,EXPR)
  2454.      open(FILEHANDLE)
  2455.      open FILEHANDLE
  2456.              Opens the file whose filename is given by EXPR,  and
  2457.              associates  it with FILEHANDLE.  If FILEHANDLE is an
  2458.              expression, its value is used as  the  name  of  the
  2459.              real  filehandle  wanted.   If  EXPR is omitted, the
  2460.              scalar variable of the same name as  the  FILEHANDLE
  2461.              contains  the filename.  If the filename begins with
  2462.              "<" or nothing, the file is opened  for  input.   If
  2463.              the filename begins with ">", the file is opened for
  2464.              output.  If the filename begins with ">>", the  file
  2465.              is  opened  for  appending.   (You  can put a '+' in
  2466.              front of the '>' or '<' to indicate  that  you  want
  2467.              both  read  and  write  access  to the file.) If the
  2468.              filename begins with "|",  the  filename  is  inter-
  2469.              preted  as a command to which output is to be piped,
  2470.              and if the filename ends with a "|", the filename is
  2471.              interpreted  as  command  which  pipes  input to us.
  2472.              (You may not have a command that pipes both  in  and
  2473.              out.) Opening '-' opens STDIN and opening '>-' opens
  2474.              STDOUT.  Open returns  non-zero  upon  success,  the
  2475.              undefined  value  otherwise.  If the open involved a
  2476.              pipe, the return value happens to be the pid of  the
  2477.              subprocess.  Examples:
  2478.  
  2479.                   $article = 100;
  2480.                   open article || die "Can't find article $article: $!\n";
  2481.                   while (<article>) {...
  2482.  
  2483.                   open(LOG, '>>/usr/spool/news/twitlog');
  2484.                                       # (log is reserved)
  2485.  
  2486.                   open(article, "caesar <$article |");
  2487.                                       # decrypt article
  2488.  
  2489.                   open(extract, "|sort >/tmp/Tmp$$");
  2490.                                       # $$ is our process#
  2491.  
  2492.                   # process argument list of files along with any includes
  2493.  
  2494.                   foreach $file (@ARGV) {
  2495.                        do process($file, 'fh00');    # no pun intended
  2496.                   }
  2497.  
  2498.                   sub process {
  2499.                        local($filename, $input) = @_;
  2500.                        $input++;      # this is a string increment
  2501.                        unless (open($input, $filename)) {
  2502.                             print STDERR "Can't open $filename: $!\n";
  2503.                             return;
  2504.                        }
  2505.                        while (<$input>) {       # note use of indirection
  2506.                             if (/^#include "(.*)"/) {
  2507.                                  do process($1, $input);
  2508.                                  next;
  2509.                             }
  2510.                             ...       # whatever
  2511.  
  2512.                        }
  2513.                   }
  2514.  
  2515.              You may also, in the Bourne shell tradition, specify
  2516.              an  EXPR beginning with ">&", in which case the rest
  2517.              of the string  is  interpreted  as  the  name  of  a
  2518.              filehandle (or file descriptor, if numeric) which is
  2519.              to be duped and opened.  You may use & after >,  >>,
  2520.              <,  +>,  +>>  and  +<.   The mode you specify should
  2521.              match the mode of the original filehandle.  Here  is
  2522.              a  script that saves, redirects, and restores STDOUT
  2523.              and STDERR:
  2524.  
  2525.                   #!/usr/bin/perl
  2526.                   open(SAVEOUT, ">&STDOUT");
  2527.                   open(SAVEERR, ">&STDERR");
  2528.  
  2529.                   open(STDOUT, ">foo.out") || die "Can't redirect stdout";
  2530.                   open(STDERR, ">&STDOUT") || die "Can't dup stdout";
  2531.  
  2532.                   select(STDERR); $| = 1;       # make unbuffered
  2533.                   select(STDOUT); $| = 1;       # make unbuffered
  2534.  
  2535.                   print STDOUT "stdout 1\n";    # this works for
  2536.                   print STDERR "stderr 1\n";    # subprocesses too
  2537.  
  2538.                   close(STDOUT);
  2539.                   close(STDERR);
  2540.  
  2541.                   open(STDOUT, ">&SAVEOUT");
  2542.                   open(STDERR, ">&SAVEERR");
  2543.  
  2544.                   print STDOUT "stdout 2\n";
  2545.                   print STDERR "stderr 2\n";
  2546.  
  2547.              If you open a pipe on the command "-",  i.e.  either
  2548.              "|-"  or  "-|", then there is an implicit fork done,
  2549.              and the return value of open is the pid of the child
  2550.              within  the  parent  process, and 0 within the child
  2551.              process.  (Use defined($pid)  to  determine  if  the
  2552.              open  was  successful.)  The filehandle behaves nor-
  2553.              mally for the parent, but i/o to that filehandle  is
  2554.              piped from/to the STDOUT/STDIN of the child process.
  2555.              In the child process the filehandle  isn't  opened--
  2556.              i/o  happens from/to the new STDOUT or STDIN.  Typi-
  2557.              cally this is used like the normal piped  open  when
  2558.              you  want to exercise more control over just how the
  2559.              pipe command gets executed, such  as  when  you  are
  2560.              running setuid, and don't want to have to scan shell
  2561.              commands for metacharacters.   The  following  pairs
  2562.              are more or less equivalent:
  2563.  
  2564.                   open(FOO, "|tr '[a-z]' '[A-Z]'");
  2565.                   open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]';
  2566.  
  2567.                   open(FOO, "cat -n '$file'|");
  2568.                   open(FOO, "-|") || exec 'cat', '-n', $file;
  2569.  
  2570.              Explicitly closing any piped filehandle  causes  the
  2571.              parent  process to wait for the child to finish, and
  2572.              returns the status value in $?.  Note: on any opera-
  2573.              tion  which  may do a fork, unflushed buffers remain
  2574.              unflushed in both processes,  which  means  you  may
  2575.              need to set $| to avoid duplicate output.
  2576.  
  2577.              The filename that is passed to open will have  lead-
  2578.              ing  and  trailing  whitespace deleted.  In order to
  2579.              open a file with arbitrary weird characters  in  it,
  2580.              it's  necessary  to protect any leading and trailing
  2581.              whitespace thusly:
  2582.  
  2583.                      $file =~ s#^(\s)#./$1#;
  2584.                      open(FOO, "< $file\0");
  2585.  
  2586.      opendir(DIRHANDLE,EXPR)
  2587.              Opens a directory named EXPR for processing by read-
  2588.              dir(),   telldir(),   seekdir(),   rewinddir()   and
  2589.              closedir().  Returns true if successful.  DIRHANDLEs
  2590.              have their own namespace separate from FILEHANDLEs.
  2591.  
  2592.      ord(EXPR)
  2593.      ord EXPR
  2594.              Returns the numeric ascii value of the first charac-
  2595.              ter of EXPR.  If EXPR is omitted, uses $_.
  2596.  
  2597.      pack(TEMPLATE,LIST)
  2598.              Takes an array or list of values and packs it into a
  2599.              binary  structure,  returning  the string containing
  2600.              the structure.  The TEMPLATE is a sequence of  char-
  2601.              acters  that  give  the order and type of values, as
  2602.              follows:
  2603.  
  2604.                   A    An ascii string, will be space padded.
  2605.                   a    An ascii string, will be null padded.
  2606.                   c    A signed char value.
  2607.                   C    An unsigned char value.
  2608.                   s    A signed short value.
  2609.                   S    An unsigned short value.
  2610.                   i    A signed integer value.
  2611.                   I    An unsigned integer value.
  2612.                   l    A signed long value.
  2613.                   L    An unsigned long value.
  2614.                   n    A short in "network" order.
  2615.                   N    A long in "network" order.
  2616.                   f    A single-precision float in the native format.
  2617.                   d    A double-precision float in the native format.
  2618.                   p    A pointer to a string.
  2619.                   v    A short in "VAX" (little-endian) order.
  2620.                   V    A long in "VAX" (little-endian) order.
  2621.                   x    A null byte.
  2622.                   X    Back up a byte.
  2623.                   @    Null fill to absolute position.
  2624.                   u    A uuencoded string.
  2625.                   b    A bit string (ascending bit order, like vec()).
  2626.                   B    A bit string (descending bit order).
  2627.                   h    A hex string (low nybble first).
  2628.                   H    A hex string (high nybble first).
  2629.  
  2630.              Each letter may optionally be followed by  a  number
  2631.              which  gives  a repeat count.  With all types except
  2632.              "a", "A", "b", "B", "h" and "H", the  pack  function
  2633.              will  gobble up that many values from the LIST.  A *
  2634.              for the repeat count means to use however many items
  2635.              are  left.   The  "a"  and "A" types gobble just one
  2636.              value, but pack it as a string of length count, pad-
  2637.              ding  with  nulls  or  spaces  as  necessary.  (When
  2638.              unpacking, "A" strips trailing spaces and nulls, but
  2639.              "a" does not.) Likewise, the "b" and "B" fields pack
  2640.              a string that many  bits  long.   The  "h"  and  "H"
  2641.              fields  pack  a string that many nybbles long.  Real
  2642.              numbers (floats  and  doubles)  are  in  the  native
  2643.              machine  format  only;  due  to  the multiplicity of
  2644.              floating formats around, and the lack of a  standard
  2645.              "network"  representation,  no  facility  for inter-
  2646.              change has been made.  This means that packed float-
  2647.              ing  point  data  written  on one machine may not be
  2648.              readable on another - even if both use IEEE floating
  2649.              point  arithmetic  (as the endian-ness of the memory
  2650.              representation is not part of the IEEE spec).   Note
  2651.              that  perl  uses  doubles internally for all numeric
  2652.              calculation, and converting from double -> float  ->
  2653.              double   will   lose   precision  (i.e.  unpack("f",
  2654.              pack("f", $foo)) will not in general equal $foo).
  2655.              Examples:
  2656.  
  2657.                   $foo = pack("cccc",65,66,67,68);
  2658.                   # foo eq "ABCD"
  2659.                   $foo = pack("c4",65,66,67,68);
  2660.                   # same thing
  2661.  
  2662.                   $foo = pack("ccxxcc",65,66,67,68);
  2663.                   # foo eq "AB\0\0CD"
  2664.  
  2665.                   $foo = pack("s2",1,2);
  2666.  
  2667.                   # "\1\0\2\0" on little-endian
  2668.                   # "\0\1\0\2" on big-endian
  2669.  
  2670.                   $foo = pack("a4","abcd","x","y","z");
  2671.                   # "abcd"
  2672.  
  2673.                   $foo = pack("aaaa","abcd","x","y","z");
  2674.                   # "axyz"
  2675.  
  2676.                   $foo = pack("a14","abcdefg");
  2677.                   # "abcdefg\0\0\0\0\0\0\0"
  2678.  
  2679.                   $foo = pack("i9pl", gmtime);
  2680.                   # a real struct tm (on my system anyway)
  2681.  
  2682.                   sub bintodec {
  2683.                       unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
  2684.                   }
  2685.              The same template may generally also be used in  the
  2686.              unpack function.
  2687.  
  2688.      pipe(READHANDLE,WRITEHANDLE)
  2689.              Opens a pair of connected pipes like the correspond-
  2690.              ing  system call.  Note that if you set up a loop of
  2691.              piped processes, deadlock can occur unless  you  are
  2692.              very  careful.   In addition, note that perl's pipes
  2693.              use stdio buffering, so you may need to  set  $|  to
  2694.              flush your WRITEHANDLE after each command, depending
  2695.              on   the   application.    [Requires   version   3.0
  2696.              patchlevel 9.]
  2697.  
  2698.      pop(ARRAY)
  2699.      pop ARRAY
  2700.              Pops and returns the last value of the array,  shor-
  2701.              tening the array by 1.  Has the same effect as
  2702.  
  2703.                   $tmp = $ARRAY[$#ARRAY--];
  2704.  
  2705.              If there are no elements in the array,  returns  the
  2706.              undefined value.
  2707.  
  2708.      print(FILEHANDLE LIST)
  2709.      print(LIST)
  2710.      print FILEHANDLE LIST
  2711.      print LIST
  2712.      print   Prints  a  string  or  a  comma-separated  list   of
  2713.              strings.     Returns    non-zero    if   successful.
  2714.              FILEHANDLE may be a scalar variable name,  in  which
  2715.              case  the variable contains the name of the filehan-
  2716.              dle, thus  introducing  one  level  of  indirection.
  2717.              (NOTE:  If  FILEHANDLE  is  a  variable and the next
  2718.              token is a term, it  may  be  misinterpreted  as  an
  2719.              operator  unless  you  interpose  a  + or put parens
  2720.              around the arguments.)  If  FILEHANDLE  is  omitted,
  2721.              prints by default to standard output (or to the last
  2722.              selected output channel--see select()).  If LIST  is
  2723.              also  omitted,  prints  $_  to  STDOUT.   To set the
  2724.              default  output  channel  to  something  other  than
  2725.              STDOUT use the select operation.  Note that, because
  2726.              print  takes  a  LIST,  anything  in  the  LIST   is
  2727.              evaluated  in  an  array context, and any subroutine
  2728.              that you call will have one or more of  its  expres-
  2729.              sions  evaluated in an array context.  Also be care-
  2730.              ful not to follow the  print  keyword  with  a  left
  2731.              parenthesis  unless you want the corresponding right
  2732.              parenthesis  to  terminate  the  arguments  to   the
  2733.              print--interpose  a  +  or put parens around all the
  2734.              arguments.
  2735.  
  2736.      printf(FILEHANDLE LIST)
  2737.      printf(LIST)
  2738.      printf FILEHANDLE LIST
  2739.      printf LIST
  2740.              Equivalent to a "print FILEHANDLE sprintf(LIST)".
  2741.  
  2742.      push(ARRAY,LIST)
  2743.              Treats ARRAY (@ is optional) as a stack, and  pushes
  2744.              the  values  of  LIST  onto  the  end of ARRAY.  The
  2745.              length of ARRAY increases by  the  length  of  LIST.
  2746.              Has the same effect as
  2747.  
  2748.                  for $value (LIST) {
  2749.                       $ARRAY[++$#ARRAY] = $value;
  2750.                  }
  2751.  
  2752.              but is more efficient.
  2753.  
  2754.      q/STRING/
  2755.      qq/STRING/
  2756.      qx/STRING/
  2757.              These are not really functions, but simply syntactic
  2758.              sugar  to let you avoid putting too many backslashes
  2759.              into quoted strings.  The q operator is  a  general-
  2760.              ized single quote, and the qq operator a generalized
  2761.              double quote.  The  qx  operator  is  a  generalized
  2762.              backquote.   Any  non-alphanumeric  delimiter can be
  2763.              used in place of /, including newline.  If the  del-
  2764.              imiter  is  an  opening  bracket or parenthesis, the
  2765.              final delimiter will be  the  corresponding  closing
  2766.              bracket  or  parenthesis.   (Embedded occurrences of
  2767.              the  closing  bracket  need  to  be  backslashed  as
  2768.              usual.) Examples:
  2769.  
  2770.                   $foo = q!I said, "You said, 'She said it.'"!;
  2771.                   $bar = q('This is it.');
  2772.                   $today = qx{ date };
  2773.                   $_ .= qq
  2774.              *** The previous line contains the naughty word "$&".\n
  2775.                        if /(ibm|apple|awk)/;      # :-)
  2776.  
  2777.      rand(EXPR)
  2778.      rand EXPR
  2779.      rand    Returns a random fractional number between 0 and the
  2780.              value  of  EXPR.  (EXPR should be positive.) If EXPR
  2781.              is omitted, returns a value between 0  and  1.   See
  2782.              also srand().
  2783.  
  2784.      read(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  2785.      read(FILEHANDLE,SCALAR,LENGTH)
  2786.              Attempts to read LENGTH bytes of data into  variable
  2787.              SCALAR  from  the specified FILEHANDLE.  Returns the
  2788.              number of bytes actually read, or undef if there was
  2789.              an  error.   SCALAR  will  be grown or shrunk to the
  2790.              length actually read.  An OFFSET may be specified to
  2791.              place  the  read  data  at some other place than the
  2792.              beginning of the  string.   This  call  is  actually
  2793.              implemented  in terms of stdio's fread call.  To get
  2794.              a true read system call, see sysread.
  2795.  
  2796.      readdir(DIRHANDLE)
  2797.      readdir DIRHANDLE
  2798.              Returns the next directory  entry  for  a  directory
  2799.              opened  by  opendir().  If used in an array context,
  2800.              returns all the rest of the entries  in  the  direc-
  2801.              tory.   If  there  are  no  more entries, returns an
  2802.              undefined value in a scalar context or a  null  list
  2803.              in an array context.
  2804.  
  2805.      readlink(EXPR)
  2806.      readlink EXPR
  2807.              Returns the value of a symbolic  link,  if  symbolic
  2808.              links are implemented.  If not, gives a fatal error.
  2809.              If there is some system error, returns the undefined
  2810.              value and sets $! (errno).  If EXPR is omitted, uses
  2811.              $_.
  2812.  
  2813.      recv(SOCKET,SCALAR,LEN,FLAGS)
  2814.              Receives a message on a socket.  Attempts to receive
  2815.              LENGTH  bytes  of data into variable SCALAR from the
  2816.              specified SOCKET filehandle.  Returns the address of
  2817.              the  sender,  or  the  undefined value if there's an
  2818.              error.  SCALAR will be grown or shrunk to the length
  2819.              actually  read.   Takes the same flags as the system
  2820.              call of the same name.
  2821.  
  2822.      redo LABEL
  2823.      redo    The redo command restarts  the  loop  block  without
  2824.              evaluating  the  conditional  again.   The  continue
  2825.              block, if any, is not executed.   If  the  LABEL  is
  2826.              omitted, the command refers to the innermost enclos-
  2827.              ing loop.  This command is normally used by programs
  2828.              that  want  to lie to themselves about what was just
  2829.              input:
  2830.  
  2831.                   # a simpleminded Pascal comment stripper
  2832.                   # (warning: assumes no { or } in strings)
  2833.                   line: while (<STDIN>) {
  2834.                        while (s|({.*}.*){.*}|$1 |) {}
  2835.                        s|{.*}| |;
  2836.                        if (s|{.*| |) {
  2837.                             $front = $_;
  2838.                             while (<STDIN>) {
  2839.                                  if (/}/) {     # end of comment?
  2840.                                       s|^|$front{|;
  2841.                                       redo line;
  2842.                                  }
  2843.                             }
  2844.                        }
  2845.                        print;
  2846.                   }
  2847.  
  2848.      rename(OLDNAME,NEWNAME)
  2849.              Changes the name of a file.  Returns 1 for  success,
  2850.              0  otherwise.  Will not work across filesystem boun-
  2851.              daries.
  2852.  
  2853.      require(EXPR)
  2854.      require EXPR
  2855.      require Includes the library file specified by EXPR,  or  by
  2856.              $_  if  EXPR is not supplied.  Has semantics similar
  2857.              to the following subroutine:
  2858.  
  2859.                   sub require {
  2860.                       local($filename) = @_;
  2861.                       return 1 if $INC{$filename};
  2862.                       local($realfilename,$result);
  2863.                       ITER: {
  2864.                        foreach $prefix (@INC) {
  2865.                            $realfilename = "$prefix/$filename";
  2866.                            if (-f $realfilename) {
  2867.                             $result = do $realfilename;
  2868.                             last ITER;
  2869.                            }
  2870.                        }
  2871.                        die "Can't find $filename in \@INC";
  2872.                       }
  2873.                       die $@ if $@;
  2874.                       die "$filename did not return true value" unless $result;
  2875.                       $INC{$filename} = $realfilename;
  2876.                       $result;
  2877.                   }
  2878.  
  2879.              Note that the file will not be included twice  under
  2880.              the same specified name.
  2881.  
  2882.      reset(EXPR)
  2883.      reset EXPR
  2884.      reset   Generally used in a continue block at the end  of  a
  2885.              loop  to  clear  variables  and reset ?? searches so
  2886.              that they work again.  The expression is interpreted
  2887.              as  a list of single characters (hyphens allowed for
  2888.              ranges).  All variables and  arrays  beginning  with
  2889.              one  of  those  letters  are reset to their pristine
  2890.              state.  If  the  expression  is  omitted,  one-match
  2891.              searches (?pattern?) are reset to match again.  Only
  2892.              resets variables or searches in the current package.
  2893.              Always returns 1.  Examples:
  2894.  
  2895.                  reset 'X';      # reset all X variables
  2896.                  reset 'a-z';    # reset lower case variables
  2897.                  reset;          # just reset ?? searches
  2898.  
  2899.              Note:  resetting  "A-Z"  is  not  recommended  since
  2900.              you'll wipe out your ARGV and ENV arrays.
  2901.  
  2902.              The use of reset on dbm associative arrays does  not
  2903.              change  the  dbm file.  (It does, however, flush any
  2904.              entries cached by perl, which may be useful  if  you
  2905.              are sharing the dbm file.  Then again, maybe not.)
  2906.  
  2907.      return LIST
  2908.              Returns from a subroutine with the value  specified.
  2909.              (Note that a subroutine can automatically return the
  2910.              value of the last expression evaluated.  That's  the
  2911.              preferred method--use of an explicit return is a bit
  2912.              slower.)
  2913.  
  2914.      reverse(LIST)
  2915.      reverse LIST
  2916.              In an array context, returns an array value consist-
  2917.              ing  of  the elements of LIST in the opposite order.
  2918.              In a scalar context, returns a string value consist-
  2919.              ing of the bytes of the first element of LIST in the
  2920.              opposite order.
  2921.  
  2922.      rewinddir(DIRHANDLE)
  2923.      rewinddir DIRHANDLE
  2924.              Sets the current position to the  beginning  of  the
  2925.              directory for the readdir() routine on DIRHANDLE.
  2926.  
  2927.      rindex(STR,SUBSTR,POSITION)
  2928.      rindex(STR,SUBSTR)
  2929.              Works just like index except  that  it  returns  the
  2930.              position  of  the  LAST occurrence of SUBSTR in STR.
  2931.              If  POSITION  is   specified,   returns   the   last
  2932.              occurrence at or before that position.
  2933.  
  2934.      rmdir(FILENAME)
  2935.      rmdir FILENAME
  2936.              Deletes the directory specified by FILENAME if it is
  2937.              empty.   If  it  succeeds it returns 1, otherwise it
  2938.              returns 0 and sets $! (errno).  If FILENAME is omit-
  2939.              ted, uses $_.
  2940.  
  2941.      s/PATTERN/REPLACEMENT/gieo
  2942.              Searches a string  for  a  pattern,  and  if  found,
  2943.              replaces  that pattern with the replacement text and
  2944.              returns the number of substitutions made.  Otherwise
  2945.              it  returns  false (0).  The "g" is optional, and if
  2946.              present, indicates that all occurrences of the  pat-
  2947.              tern  are to be replaced.  The "i" is also optional,
  2948.              and if present, indicates that  matching  is  to  be
  2949.              done  in  a  case-insensitive  manner.   The  "e" is
  2950.              likewise optional, and if  present,  indicates  that
  2951.              the  replacement  string  is  to  be evaluated as an
  2952.              expression  rather  than  just  as  a  double-quoted
  2953.              string.   Any non-alphanumeric delimiter may replace
  2954.              the slashes; if single quotes are used, no interpre-
  2955.              tation  is  done  on  the  replacement string (the e
  2956.              modifier overrides this, however); if backquotes are
  2957.              used, the replacement string is a command to execute
  2958.              whose output will be used as the actual  replacement
  2959.              text.   If  no  string is specified via the =~ or !~
  2960.              operator, the $_ string is  searched  and  modified.
  2961.              (The string specified with =~ must be a scalar vari-
  2962.              able, an array element, or an assignment to  one  of
  2963.              those,  i.e. an lvalue.) If the pattern contains a $
  2964.              that looks like a variable rather  than  an  end-of-
  2965.              string  test, the variable will be interpolated into
  2966.              the pattern at run-time.  If you only want the  pat-
  2967.              tern  compiled  once  the first time the variable is
  2968.              interpolated, add an "o" at the end.  If the PATTERN
  2969.              evaluates to a null string, the most recent success-
  2970.              ful regular expression is used  instead.   See  also
  2971.              the section on regular expressions.  Examples:
  2972.  
  2973.                  s/\bgreen\b/mauve/g;      # don't change wintergreen
  2974.  
  2975.                  $path =~ s|/usr/bin|/usr/local/bin|;
  2976.  
  2977.                  s/Login: $foo/Login: $bar/; # run-time pattern
  2978.  
  2979.                  ($foo = $bar) =~ s/bar/foo/;
  2980.  
  2981.                  $_ = 'abc123xyz';
  2982.                  s/\d+/$&*2/e;        # yields 'abc246xyz'
  2983.                  s/\d+/sprintf("%5d",$&)/e;     # yields 'abc  246xyz'
  2984.                  s/\w/$& x 2/eg;      # yields 'aabbcc  224466xxyyzz'
  2985.  
  2986.                  s/([^ ]*) *([^ ]*)/$2 $1/;     # reverse 1st two fields
  2987.  
  2988.              (Note the use of $ instead of \ in the last example.
  2989.              See section on Regular Expressions.)
  2990.  
  2991.      scalar(EXPR)
  2992.              Forces EXPR to be interpreted in  a  scalar  context
  2993.              and returns the value of EXPR.
  2994.  
  2995.      seek(FILEHANDLE,POSITION,WHENCE)
  2996.              Randomly positions the file pointer for  FILEHANDLE,
  2997.              just like the fseek() call of stdio.  FILEHANDLE may
  2998.              be an expression whose value gives the name  of  the
  2999.              filehandle.  Returns 1 upon success, 0 otherwise.
  3000.  
  3001.      seekdir(DIRHANDLE,POS)
  3002.              Sets the current position for the readdir()  routine
  3003.              on  DIRHANDLE.   POS  must  be  a  value returned by
  3004.              telldir().  Has  the  same  caveats  about  possible
  3005.              directory  compaction  as  the  corresponding system
  3006.              library routine.
  3007.  
  3008.      select(FILEHANDLE)
  3009.      select  Returns the currently selected filehandle.  Sets the
  3010.              current default filehandle for output, if FILEHANDLE
  3011.              is supplied.  This has two effects: first,  a  write
  3012.              or a print without a filehandle will default to this
  3013.              FILEHANDLE.  Second, references to variables related
  3014.              to  output  will  refer to this output channel.  For
  3015.              example, if you have to set the top of  form  format
  3016.              for  more  than one output channel, you might do the
  3017.              following:
  3018.  
  3019.                   select(REPORT1);
  3020.                   $^ = 'report1_top';
  3021.                   select(REPORT2);
  3022.                   $^ = 'report2_top';
  3023.  
  3024.              FILEHANDLE may be an expression  whose  value  gives
  3025.              the name of the actual filehandle.  Thus:
  3026.  
  3027.                   $oldfh = select(STDERR); $| = 1; select($oldfh);
  3028.  
  3029.      select(RBITS,WBITS,EBITS,TIMEOUT)
  3030.              This calls the select system call with the  bitmasks
  3031.              specified,  which  can be constructed using fileno()
  3032.              and vec(), along these lines:
  3033.  
  3034.                   $rin = $win = $ein = '';
  3035.                   vec($rin,fileno(STDIN),1) = 1;
  3036.                   vec($win,fileno(STDOUT),1) = 1;
  3037.                   $ein = $rin | $win;
  3038.  
  3039.              If you want to select on many filehandles you  might
  3040.              wish to write a subroutine:
  3041.  
  3042.                   sub fhbits {
  3043.                       local(@fhlist) = split(' ',$_[0]);
  3044.                       local($bits);
  3045.                       for (@fhlist) {
  3046.                        vec($bits,fileno($_),1) = 1;
  3047.                       }
  3048.                       $bits;
  3049.                   }
  3050.                   $rin = &fhbits('STDIN TTY SOCK');
  3051.  
  3052.              The usual idiom is:
  3053.  
  3054.                   ($nfound,$timeleft) =
  3055.                     select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
  3056.  
  3057.              or to block until something becomes ready:
  3058.  
  3059.                   $nfound = select($rout=$rin, $wout=$win,
  3060.                                  $eout=$ein, undef);
  3061.  
  3062.              Any of the bitmasks can also be undef.  The timeout,
  3063.              if  specified,  is  in  seconds,  which may be frac-
  3064.              tional.  NOTE: not all implementations  are  capable
  3065.              of  returning  the  $timeleft.   If not, they always
  3066.              return $timeleft equal to the supplied $timeout.
  3067.  
  3068.      semctl(ID,SEMNUM,CMD,ARG)
  3069.              Calls the System V IPC function semctl.  If  CMD  is
  3070.              &IPC_STAT  or  &GETALL,  then ARG must be a variable
  3071.              which will hold the returned semid_ds  structure  or
  3072.              semaphore  value  array.   Returns  like  ioctl: the
  3073.              undefined value for error, "0 but true" for zero, or
  3074.              the actual return value otherwise.
  3075.  
  3076.      semget(KEY,NSEMS,SIZE,FLAGS)
  3077.              Calls the System V IPC function semget.  Returns the
  3078.              semaphore  id, or the undefined value if there is an
  3079.              error.
  3080.  
  3081.      semop(KEY,OPSTRING)
  3082.              Calls the System V IPC  function  semop  to  perform
  3083.              semaphore  operations such as signaling and waiting.
  3084.              OPSTRING must be a packed array of semop structures.
  3085.              Each   semop   structure   can   be  generated  with
  3086.              'pack("sss",  $semnum,  $semop,   $semflag)'.    The
  3087.              number  of  semaphore  operations  is implied by the
  3088.              length of OPSTRING.  Returns true if successful,  or
  3089.              false if there is an error.  As an example, the fol-
  3090.              lowing code waits on semaphore $semnum of  semaphore
  3091.              id $semid:
  3092.  
  3093.                   $semop = pack("sss", $semnum, -1, 0);
  3094.                   die "Semaphore trouble: $!\n" unless semop($semid, $semop);
  3095.  
  3096.              To signal the semaphore, replace "-1" with "1".
  3097.  
  3098.      send(SOCKET,MSG,FLAGS,TO)
  3099.      send(SOCKET,MSG,FLAGS)
  3100.              Sends a message on a socket.  Takes the  same  flags
  3101.              as the system call of the same name.  On unconnected
  3102.              sockets you must specify a destination to  send  TO.
  3103.              Returns  the number of characters sent, or the unde-
  3104.              fined value if there is an error.
  3105.  
  3106.      setpgrp(PID,PGRP)
  3107.              Sets the current process  group  for  the  specified
  3108.              PID,  0  for  the  current  process.  Will produce a
  3109.              fatal error if used on a machine that doesn't imple-
  3110.              ment setpgrp(2).
  3111.  
  3112.      setpriority(WHICH,WHO,PRIORITY)
  3113.              Sets the current priority for a process,  a  process
  3114.              group,  or  a user.  (See setpriority(2).) Will pro-
  3115.              duce a fatal error if used on a machine that doesn't
  3116.              implement setpriority(2).
  3117.  
  3118.      setsockopt(SOCKET,LEVEL,OPTNAME,OPTVAL)
  3119.              Sets the socket option requested.  Returns undefined
  3120.              if  there  is  an error.  OPTVAL may be specified as
  3121.              undef if you don't want to pass an argument.
  3122.  
  3123.      shift(ARRAY)
  3124.      shift ARRAY
  3125.      shift   Shifts the first value of the array off and  returns
  3126.              it,  shortening the array by 1 and moving everything
  3127.              down.  If  there  are  no  elements  in  the  array,
  3128.              returns  the  undefined value.  If ARRAY is omitted,
  3129.              shifts the @ARGV array in the main program, and  the
  3130.              @_  array in subroutines.  (This is determined lexi-
  3131.              cally.)  See  also  unshift(),  push()  and   pop().
  3132.              Shift()  and unshift() do the same thing to the left
  3133.              end of an array that push()  and  pop()  do  to  the
  3134.              right end.
  3135.  
  3136.      shmctl(ID,CMD,ARG)
  3137.              Calls the System V IPC function shmctl.  If  CMD  is
  3138.              &IPC_STAT,  then  ARG  must be a variable which will
  3139.              hold the returned shmid_ds structure.  Returns  like
  3140.              ioctl:  the  undefined value for error, "0 but true"
  3141.              for zero, or the actual return value otherwise.
  3142.  
  3143.      shmget(KEY,SIZE,FLAGS)
  3144.              Calls the System V IPC function shmget.  Returns the
  3145.              shared  memory segment id, or the undefined value if
  3146.              there is an error.
  3147.  
  3148.      shmread(ID,VAR,POS,SIZE)
  3149.      shmwrite(ID,STRING,POS,SIZE)
  3150.              Reads or writes the System V shared  memory  segment
  3151.              ID  starting  at  position  POS  for  size  SIZE  by
  3152.              attaching to it, copying in/out, and detaching  from
  3153.              it.  When reading, VAR must be a variable which will
  3154.              hold the data read.  When writing, if STRING is  too
  3155.              long,  only  SIZE  bytes  are used; if STRING is too
  3156.              short, nulls are written to  fill  out  SIZE  bytes.
  3157.              Return  true  if successful, or false if there is an
  3158.              error.
  3159.  
  3160.      shutdown(SOCKET,HOW)
  3161.              Shuts down a socket connection in the  manner  indi-
  3162.              cated  by  HOW, which has the same interpretation as
  3163.              in the system call of the same name.
  3164.  
  3165.      sin(EXPR)
  3166.      sin EXPR
  3167.              Returns the sine of EXPR (expressed in radians).  If
  3168.              EXPR is omitted, returns sine of $_.
  3169.  
  3170.      sleep(EXPR)
  3171.      sleep EXPR
  3172.      sleep   Causes the script to sleep for EXPR seconds, or for-
  3173.              ever  if no EXPR.  May be interrupted by sending the
  3174.              process a SIGALRM.  Returns the  number  of  seconds
  3175.              actually slept.  You probably cannot mix alarm() and
  3176.              sleep() calls, since sleep()  is  often  implemented
  3177.              using alarm().
  3178.  
  3179.      socket(SOCKET,DOMAIN,TYPE,PROTOCOL)
  3180.              Opens a socket of the specified kind and attaches it
  3181.              to filehandle SOCKET.  DOMAIN, TYPE and PROTOCOL are
  3182.              specified the same as for the  system  call  of  the
  3183.              same name.  You may need to run h2ph on sys/socket.h
  3184.              to get the proper values handy  in  a  perl  library
  3185.              file.   Return  true if successful.  See the example
  3186.              in the section on Interprocess Communication.
  3187.  
  3188.      socketpair(SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL)
  3189.              Creates an unnamed pair of sockets in the  specified
  3190.              domain,  of  the  specified  type.  DOMAIN, TYPE and
  3191.              PROTOCOL are specified the same as  for  the  system
  3192.              call  of  the same name.  If unimplemented, yields a
  3193.              fatal error.  Return true if successful.
  3194.  
  3195.      sort(SUBROUTINE LIST)
  3196.      sort(LIST)
  3197.      sort SUBROUTINE LIST
  3198.      sort BLOCK LIST
  3199.      sort LIST
  3200.              Sorts the LIST and returns the sorted  array  value.
  3201.              Nonexistent  values  of arrays are stripped out.  If
  3202.              SUBROUTINE or BLOCK is omitted,  sorts  in  standard
  3203.              string  comparison  order.   If SUBROUTINE is speci-
  3204.              fied, gives the name of a subroutine that returns an
  3205.              integer  less  than,  equal  to,  or greater than 0,
  3206.              depending on how the elements of the array are to be
  3207.              ordered.   (The  <=> and cmp operators are extremely
  3208.              useful in such routines.) SUBROUTINE may be a scalar
  3209.              variable  name, in which case the value provides the
  3210.              name of the subroutine to use.  In place of  a  SUB-
  3211.              ROUTINE   name,  you  can  provide  a  BLOCK  as  an
  3212.              anonymous, in-line sort subroutine.
  3213.  
  3214.              In the interests of efficiency  the  normal  calling
  3215.              code for subroutines is bypassed, with the following
  3216.              effects: the subroutine may not be a recursive  sub-
  3217.              routine,  and  the  two  elements to be compared are
  3218.              passed into the subroutine not via @_ but as $a  and
  3219.              $b  (see  example below).  They are passed by refer-
  3220.              ence so don't modify $a and $b.
  3221.  
  3222.              Examples:
  3223.  
  3224.                   # sort lexically
  3225.                   @articles = sort @files;
  3226.  
  3227.                   # same thing, but with explicit sort routine
  3228.                   @articles = sort {$a cmp $b;} @files;
  3229.  
  3230.                   # same thing in reversed order
  3231.                   @articles = sort {$b cmp $a;} @files;
  3232.  
  3233.                   # sort numerically ascending
  3234.                   @articles = sort {$a <=> $b;} @files;
  3235.  
  3236.                   # sort numerically descending
  3237.                   @articles = sort {$b <=> $a;} @files;
  3238.  
  3239.                   # sort using explicit subroutine name
  3240.                   sub byage {
  3241.                       $age{$a} <=> $age{$b};    # presuming integers
  3242.                   }
  3243.                   @sortedclass = sort byage @class;
  3244.  
  3245.                   sub reverse { $b cmp $a; }
  3246.                   @harry = ('dog','cat','x','Cain','Abel');
  3247.                   @george = ('gone','chased','yz','Punished','Axed');
  3248.                   print sort @harry;
  3249.                        # prints AbelCaincatdogx
  3250.                   print sort reverse @harry;
  3251.                        # prints xdogcatCainAbel
  3252.                   print sort @george, 'to', @harry;
  3253.                        # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
  3254.  
  3255.      splice(ARRAY,OFFSET,LENGTH,LIST)
  3256.      splice(ARRAY,OFFSET,LENGTH)
  3257.      splice(ARRAY,OFFSET)
  3258.              Removes the elements designated by OFFSET and LENGTH
  3259.              from  an  array, and replaces them with the elements
  3260.              of LIST, if any.  Returns the elements removed  from
  3261.              the array.  The array grows or shrinks as necessary.
  3262.              If LENGTH is omitted, removes everything from OFFSET
  3263.              onward.   The following equivalencies hold (assuming
  3264.              $[ == 0):
  3265.  
  3266.                   push(@a,$x,$y)                splice(@a,$#a+1,0,$x,$y)
  3267.                   pop(@a)                       splice(@a,-1)
  3268.                   shift(@a)                     splice(@a,0,1)
  3269.                   unshift(@a,$x,$y)             splice(@a,0,0,$x,$y)
  3270.                   $a[$x] = $y                   splice(@a,$x,1,$y);
  3271.  
  3272.              Example, assuming array lengths are passed before arrays:
  3273.  
  3274.                   sub aeq { # compare two array values
  3275.                        local(@a) = splice(@_,0,shift);
  3276.                        local(@b) = splice(@_,0,shift);
  3277.                        return 0 unless @a == @b;     # same len?
  3278.                        while (@a) {
  3279.                            return 0 if pop(@a) ne pop(@b);
  3280.                        }
  3281.                        return 1;
  3282.                   }
  3283.                   if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
  3284.  
  3285.      split(/PATTERN/,EXPR,LIMIT)
  3286.      split(/PATTERN/,EXPR)
  3287.      split(/PATTERN/)
  3288.      split   Splits a  string  into  an  array  of  strings,  and
  3289.              returns  it.   (If  not in an array context, returns
  3290.              the number of fields found and splits  into  the  @_
  3291.              array.   (In  an  array  context,  you can force the
  3292.              split into @_ by using ?? as the pattern delimiters,
  3293.              but  it  still returns the array value.)) If EXPR is
  3294.              omitted, splits the $_ string.  If PATTERN  is  also
  3295.              omitted,  splits  on  whitespace (/[ \t\n]+/).  Any-
  3296.              thing matching PATTERN is taken to  be  a  delimiter
  3297.              separating the fields.  (Note that the delimiter may
  3298.              be longer than one character.) If  LIMIT  is  speci-
  3299.              fied,  splits  into  no  more  than that many fields
  3300.              (though it may  split  into  fewer).   If  LIMIT  is
  3301.              unspecified,   trailing  null  fields  are  stripped
  3302.              (which potential users of pop()  would  do  well  to
  3303.              remember).   A pattern matching the null string (not
  3304.              to be confused with a null pattern //, which is just
  3305.              one  member  of  the set of patterns matching a null
  3306.              string) will split the value of EXPR  into  separate
  3307.              characters  at  each point it matches that way.  For
  3308.              example:
  3309.  
  3310.                   print join(':', split(/ */, 'hi there'));
  3311.  
  3312.              produces the output 'h:i:t:h:e:r:e'.
  3313.  
  3314.              The LIMIT parameter can be used to partially split a
  3315.              line
  3316.  
  3317.                   ($login, $passwd, $remainder) = split(/:/, $_, 3);
  3318.  
  3319.              (When assigning to a list, if LIMIT is omitted, perl
  3320.              supplies a LIMIT one larger than the number of vari-
  3321.              ables in the list, to avoid unnecessary  work.   For
  3322.              the  list  above LIMIT would have been 4 by default.
  3323.              In time critical applications it behooves you not to
  3324.              split into more fields than you really need.)
  3325.  
  3326.              If  the  PATTERN  contains  parentheses,  additional
  3327.              array  elements  are created from each matching sub-
  3328.              string in the delimiter.
  3329.  
  3330.                   split(/([,-])/,"1-10,20");
  3331.  
  3332.              produces the array value
  3333.  
  3334.                   (1,'-',10,',',20)
  3335.  
  3336.              The  pattern  /PATTERN/  may  be  replaced  with  an
  3337.              expression to specify patterns that vary at runtime.
  3338.              (To  do   runtime   compilation   only   once,   use
  3339.              /$variable/o.) As a special case, specifying a space
  3340.              (' ') will split on white space just as  split  with
  3341.              no  arguments does, but leading white space does NOT
  3342.              produce a null first field.  Thus, split(' ') can be
  3343.              used  to  emulate  awk's  default  behavior, whereas
  3344.              split(/ /) will give you as many null initial fields
  3345.              as there are leading spaces.
  3346.  
  3347.              Example:
  3348.  
  3349.                   open(passwd, '/etc/passwd');
  3350.                   while (<passwd>) {
  3351.                        ($login, $passwd, $uid, $gid, $gcos, $home, $shell)
  3352.                             = split(/:/);
  3353.                        ...
  3354.                   }
  3355.  
  3356.              (Note that $shell above will still have a newline on
  3357.              it.  See chop().) See also join.
  3358.  
  3359.      sprintf(FORMAT,LIST)
  3360.              Returns a string formatted by the usual printf  con-
  3361.              ventions.  The * character is not supported.
  3362.  
  3363.      sqrt(EXPR)
  3364.      sqrt EXPR
  3365.              Return the square root of EXPR.  If EXPR is omitted,
  3366.              returns square root of $_.
  3367.  
  3368.      srand(EXPR)
  3369.      srand EXPR
  3370.              Sets the random number seed for the  rand  operator.
  3371.              If EXPR is omitted, does srand(time).
  3372.  
  3373.      stat(FILEHANDLE)
  3374.      stat FILEHANDLE
  3375.      stat(EXPR)
  3376.      stat SCALARVARIABLE
  3377.              Returns a 13-element array giving the statistics for
  3378.              a  file,  either  the file opened via FILEHANDLE, or
  3379.              named by EXPR.  Typically used as follows:
  3380.  
  3381.                  ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
  3382.                     $atime,$mtime,$ctime,$blksize,$blocks)
  3383.                         = stat($filename);
  3384.  
  3385.              If stat is passed the special filehandle  consisting
  3386.              of  an  underline,  no stat is done, but the current
  3387.              contents of the stat structure from the last stat or
  3388.              filetest are returned.  Example:
  3389.  
  3390.                   if (-x $file && (($d) = stat(_)) && $d < 0) {
  3391.                        print "$file is executable NFS file\n";
  3392.                   }
  3393.  
  3394.              (This only works on machines for  which  the  device
  3395.              number is negative under NFS.)
  3396.  
  3397.      study(SCALAR)
  3398.      study SCALAR
  3399.      study   Takes extra time to study SCALAR ($_ if unspecified)
  3400.              in anticipation of doing many pattern matches on the
  3401.              string before it is next modified.  This may or  may
  3402.              not save time, depending on the nature and number of
  3403.              patterns you are searching on, and on the  distribu-
  3404.              tion  of  character  frequencies in the string to be
  3405.              searched--you probably want to compare runtimes with
  3406.              and  without  it  to  see  which runs faster.  Those
  3407.              loops which scan for  many  short  constant  strings
  3408.              (including  the  constant parts of more complex pat-
  3409.              terns) will benefit most.  You  may  have  only  one
  3410.              study  active  at  a  time--if you study a different
  3411.              scalar the first is  "unstudied".   (The  way  study
  3412.              works  is  this: a linked list of every character in
  3413.              the string to be searched is made, so we  know,  for
  3414.              example,  where  all  the  'k' characters are.  From
  3415.              each  search  string,  the   rarest   character   is
  3416.              selected, based on some static frequency tables con-
  3417.              structed from some  C  programs  and  English  text.
  3418.              Only those places that contain this "rarest" charac-
  3419.              ter are examined.)
  3420.  
  3421.              For example, here is a loop which inserts index pro-
  3422.              ducing  entries before any line containing a certain
  3423.              pattern:
  3424.  
  3425.                   while (<>) {
  3426.                        study;
  3427.                        print ".IX foo\n" if /\bfoo\b/;
  3428.                        print ".IX bar\n" if /\bbar\b/;
  3429.                        print ".IX blurfl\n" if /\bblurfl\b/;
  3430.                        ...
  3431.                        print;
  3432.                   }
  3433.  
  3434.              In searching for /\bfoo\b/, only those locations  in
  3435.              $_  that  contain 'f' will be looked at, because 'f'
  3436.              is rarer than 'o'.  In general, this is  a  big  win
  3437.              except  in pathological cases.  The only question is
  3438.              whether it saves you more time than it took to build
  3439.              the linked list in the first place.
  3440.  
  3441.              Note that if you have to look for strings  that  you
  3442.              don't  know  till  runtime,  you can build an entire
  3443.              loop as a string and eval that to avoid  recompiling
  3444.              all your patterns all the time.  Together with unde-
  3445.              fining $/ to input entire files as one record,  this
  3446.              can be very fast, often faster than specialized pro-
  3447.              grams like fgrep.  The following  scans  a  list  of
  3448.              files  (@files)  for  a  list of words (@words), and
  3449.              prints out the names of those files that  contain  a
  3450.              match:
  3451.  
  3452.                   $search = 'while (<>) { study;';
  3453.                   foreach $word (@words) {
  3454.                       $search .= "++\$seen{\$ARGV} if /\b$word\b/;\n";
  3455.                   }
  3456.                   $search .= "}";
  3457.                   @ARGV = @files;
  3458.                   undef $/;
  3459.                   eval $search;       # this screams
  3460.                   $/ = "\n";          # put back to normal input delim
  3461.                   foreach $file (sort keys(%seen)) {
  3462.                       print $file, "\n";
  3463.                   }
  3464.  
  3465.      substr(EXPR,OFFSET,LEN)
  3466.      substr(EXPR,OFFSET)
  3467.              Extracts a substring out of  EXPR  and  returns  it.
  3468.              First  character  is at offset 0, or whatever you've
  3469.              set $[ to.  If OFFSET is negative, starts  that  far
  3470.              from  the  end  of  the  string.  If LEN is omitted,
  3471.              returns everything to the end of  the  string.   You
  3472.              can use the substr() function as an lvalue, in which
  3473.              case EXPR must be an lvalue.  If  you  assign  some-
  3474.              thing  shorter than LEN, the string will shrink, and
  3475.              if you assign something longer than LEN, the  string
  3476.              will grow to accommodate it.  To keep the string the
  3477.              same length you may need to pad or chop  your  value
  3478.              using sprintf().
  3479.  
  3480.      symlink(OLDFILE,NEWFILE)
  3481.              Creates a new filename symbolically  linked  to  the
  3482.              old  filename.   Returns 1 for success, 0 otherwise.
  3483.              On systems that don't support symbolic  links,  pro-
  3484.              duces a fatal error at run time.  To check for that,
  3485.              use eval:
  3486.  
  3487.                   $symlink_exists = (eval 'symlink("","");', $@ eq '');
  3488.  
  3489.      syscall(LIST)
  3490.      syscall LIST
  3491.              Calls the system call specified as the first element
  3492.              of the list, passing the remaining elements as argu-
  3493.              ments to the system call.   If  unimplemented,  pro-
  3494.              duces  a fatal error.  The arguments are interpreted
  3495.              as follows: if a  given  argument  is  numeric,  the
  3496.              argument  is  passed as an int.  If not, the pointer
  3497.              to the string value is passed.  You are  responsible
  3498.              to make sure a string is pre-extended long enough to
  3499.              receive any result that  might  be  written  into  a
  3500.              string.   If your integer arguments are not literals
  3501.              and have never been interpreted in  a  numeric  con-
  3502.              text, you may need to add 0 to them to force them to
  3503.              look like numbers.
  3504.  
  3505.                   require 'syscall.ph';         # may need to run h2ph
  3506.                   syscall(&SYS_write, fileno(STDOUT), "hi there\n", 9);
  3507.  
  3508.      sysread(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  3509.      sysread(FILEHANDLE,SCALAR,LENGTH)
  3510.              Attempts to read LENGTH bytes of data into  variable
  3511.              SCALAR from the specified FILEHANDLE, using the sys-
  3512.              tem call read(2).  It bypasses stdio, so mixing this
  3513.              with  other  kinds  of  reads  may  cause confusion.
  3514.              Returns the number of bytes actually read, or  undef
  3515.              if  there  was  an  error.   SCALAR will be grown or
  3516.              shrunk to the length actually read.  An  OFFSET  may
  3517.              be  specified  to  place the read data at some other
  3518.              place than the beginning of the string.
  3519.  
  3520.      system(LIST)
  3521.      system LIST
  3522.              Does exactly the same thing as  "exec  LIST"  except
  3523.              that  a  fork  is done first, and the parent process
  3524.              waits for the child process to complete.  Note  that
  3525.              argument  processing  varies depending on the number
  3526.              of arguments.  The return value is the  exit  status
  3527.              of  the  program as returned by the wait() call.  To
  3528.              get the actual exit value divide by 256.   See  also
  3529.              exec.
  3530.  
  3531.      syswrite(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  3532.      syswrite(FILEHANDLE,SCALAR,LENGTH)
  3533.              Attempts to write LENGTH bytes of data from variable
  3534.              SCALAR to the specified FILEHANDLE, using the system
  3535.              call write(2).  It bypasses stdio,  so  mixing  this
  3536.              with prints may cause confusion.  Returns the number
  3537.              of bytes actually written, or undef if there was  an
  3538.              error.  An OFFSET may be specified to place the read
  3539.              data at some other place than the beginning  of  the
  3540.              string.
  3541.  
  3542.      tell(FILEHANDLE)
  3543.      tell FILEHANDLE
  3544.      tell    Returns the current file  position  for  FILEHANDLE.
  3545.              FILEHANDLE  may  be  an expression whose value gives
  3546.              the name of the actual filehandle.  If FILEHANDLE is
  3547.              omitted, assumes the file last read.
  3548.  
  3549.      telldir(DIRHANDLE)
  3550.      telldir DIRHANDLE
  3551.              Returns the current position of the  readdir()  rou-
  3552.              tines on DIRHANDLE.  Value may be given to seekdir()
  3553.              to access a particular location in a directory.  Has
  3554.              the same caveats about possible directory compaction
  3555.              as the corresponding system library routine.
  3556.  
  3557.      time    Returns  the  number  of  non-leap   seconds   since
  3558.              00:00:00 UTC, January 1, 1970.  Suitable for feeding
  3559.              to gmtime() and localtime().
  3560.  
  3561.      times   Returns a four-element array  giving  the  user  and
  3562.              system  times,  in seconds, for this process and the
  3563.              children of this process.
  3564.  
  3565.                  ($user,$system,$cuser,$csystem) = times;
  3566.  
  3567.      tr/SEARCHLIST/REPLACEMENTLIST/cds
  3568.      y/SEARCHLIST/REPLACEMENTLIST/cds
  3569.              Translates all occurrences of the  characters  found
  3570.              in  the search list with the corresponding character
  3571.              in the replacement list.  It returns the  number  of
  3572.              characters  replaced  or  deleted.   If no string is
  3573.              specified via the =~ or !~ operator, the  $_  string
  3574.              is  translated.   (The string specified with =~ must
  3575.              be a  scalar  variable,  an  array  element,  or  an
  3576.              assignment to one of those, i.e. an lvalue.) For sed
  3577.              devotees, y is provided as a synonym for tr.
  3578.  
  3579.              If the c modifier is specified, the SEARCHLIST char-
  3580.              acter  set  is  complemented.   If the d modifier is
  3581.              specified, any characters  specified  by  SEARCHLIST
  3582.              that  are  not found in REPLACEMENTLIST are deleted.
  3583.              (Note that this is slightly more flexible  than  the
  3584.              behavior  of some tr programs, which delete anything
  3585.              they find in  the  SEARCHLIST,  period.)  If  the  s
  3586.              modifier  is specified, sequences of characters that
  3587.              were translated to the same character  are  squashed
  3588.              down to 1 instance of the character.
  3589.  
  3590.              If the d modifier was used, the  REPLACEMENTLIST  is
  3591.              always interpreted exactly as specified.  Otherwise,
  3592.              if the REPLACEMENTLIST is  shorter  than  the  SEAR-
  3593.              CHLIST, the final character is replicated till it is
  3594.              long enough.  If the REPLACEMENTLIST  is  null,  the
  3595.              SEARCHLIST is replicated.  This latter is useful for
  3596.              counting characters in a  class,  or  for  squashing
  3597.              character sequences in a class.
  3598.  
  3599.              Examples:
  3600.  
  3601.                  $ARGV[1] =~ y/A-Z/a-z/;   # canonicalize to lower case
  3602.  
  3603.                  $cnt = tr/*/*/;           # count the stars in $_
  3604.  
  3605.                  $cnt = tr/0-9//;          # count the digits in $_
  3606.  
  3607.                  tr/a-zA-Z//s;             # bookkeeper -> bokeper
  3608.  
  3609.                  ($HOST = $host) =~ tr/a-z/A-Z/;
  3610.  
  3611.                  y/a-zA-Z/ /cs;            # change non-alphas to single space
  3612.  
  3613.                  tr/\200-\377/\0-\177/;    # delete 8th bit
  3614.  
  3615.      truncate(FILEHANDLE,LENGTH)
  3616.      truncate(EXPR,LENGTH)
  3617.              Truncates the file opened on FILEHANDLE, or named by
  3618.              EXPR,  to  the  specified  length.  Produces a fatal
  3619.              error if truncate isn't implemented on your system.
  3620.  
  3621.      umask(EXPR)
  3622.      umask EXPR
  3623.      umask   Sets the umask for the process and returns  the  old
  3624.              one.   If  EXPR  is  omitted, merely returns current
  3625.              umask.
  3626.  
  3627.      undef(EXPR)
  3628.      undef EXPR
  3629.      undef   Undefines the  value  of  EXPR,  which  must  be  an
  3630.              lvalue.   Use  only  on  a  scalar  value, an entire
  3631.              array, or a subroutine name (using &).  (Undef  will
  3632.              probably  not  do what you expect on most predefined
  3633.              variables or dbm array values.) Always  returns  the
  3634.              undefined  value.   You  can omit the EXPR, in which
  3635.              case nothing is undefined,  but  you  still  get  an
  3636.              undefined value that you could, for instance, return
  3637.              from a subroutine.  Examples:
  3638.  
  3639.                   undef $foo;
  3640.                   undef $bar{'blurfl'};
  3641.                   undef @ary;
  3642.                   undef %assoc;
  3643.                   undef &mysub;
  3644.                   return (wantarray ? () : undef) if $they_blew_it;
  3645.  
  3646.      unlink(LIST)
  3647.      unlink LIST
  3648.              Deletes a list of  files.   Returns  the  number  of
  3649.              files successfully deleted.
  3650.  
  3651.                   $cnt = unlink 'a', 'b', 'c';
  3652.                   unlink @goners;
  3653.                   unlink <*.bak>;
  3654.  
  3655.              Note: unlink will not delete directories unless  you
  3656.              are  superuser  and the -U flag is supplied to perl.
  3657.              Even if these conditions are  met,  be  warned  that
  3658.              unlinking  a  directory  can  inflict damage on your
  3659.              filesystem.  Use rmdir instead.
  3660.  
  3661.      unpack(TEMPLATE,EXPR)
  3662.              Unpack does the reverse of pack: it takes  a  string
  3663.              representing  a structure and expands it out into an
  3664.              array value,  returning  the  array  value.   (In  a
  3665.              scalar  context,  it  merely returns the first value
  3666.              produced.) The TEMPLATE has the same  format  as  in
  3667.              the  pack  function.   Here's a subroutine that does
  3668.              substring:
  3669.  
  3670.                   sub substr {
  3671.                        local($what,$where,$howmuch) = @_;
  3672.                        unpack("x$where a$howmuch", $what);
  3673.                   }
  3674.  
  3675.              and then there's
  3676.  
  3677.                   sub ord { unpack("c",$_[0]); }
  3678.  
  3679.              In addition, you may prefix a field with a %<number>
  3680.              to indicate that you want a <number>-bit checksum of
  3681.              the items instead of the items themselves.   Default
  3682.              is  a  16-bit  checksum.  For example, the following
  3683.              computes the same number as the System  V  sum  pro-
  3684.              gram:
  3685.  
  3686.                   while (<>) {
  3687.                       $checksum += unpack("%16C*", $_);
  3688.                   }
  3689.                   $checksum %= 65536;
  3690.  
  3691.      unshift(ARRAY,LIST)
  3692.              Does the opposite of a shift.  Or the opposite of  a
  3693.              push,  depending  on  how  you look at it.  Prepends
  3694.              list to the front of  the  array,  and  returns  the
  3695.              number of elements in the new array.
  3696.  
  3697.                   unshift(ARGV, '-e') unless $ARGV[0] =~ /^-/;
  3698.  
  3699.      utime(LIST)
  3700.      utime LIST
  3701.              Changes the access and modification  times  on  each
  3702.              file  of a list of files.  The first two elements of
  3703.              the list must be the NUMERICAL access and  modifica-
  3704.              tion  times,  in  that order.  Returns the number of
  3705.              files successfully changed.  The inode  modification
  3706.              time of each file is set to the current time.  Exam-
  3707.              ple of a "touch" command:
  3708.  
  3709.                   #!/usr/bin/perl
  3710.                   $now = time;
  3711.                   utime $now, $now, @ARGV;
  3712.  
  3713.      values(ASSOC_ARRAY)
  3714.      values ASSOC_ARRAY
  3715.              Returns a normal array consisting of all the  values
  3716.              of  the  named  associative  array.   The values are
  3717.              returned in an apparently random order,  but  it  is
  3718.              the  same order as either the keys() or each() func-
  3719.              tion would produce on  the  same  array.   See  also
  3720.              keys() and each().
  3721.  
  3722.      vec(EXPR,OFFSET,BITS)
  3723.              Treats a string as a vector  of  unsigned  integers,
  3724.              and  returns  the  value  of the bitfield specified.
  3725.              May also be assigned to.  BITS must be  a  power  of
  3726.              two from 1 to 32.
  3727.  
  3728.              Vectors created with vec() can also  be  manipulated
  3729.              with  the  logical  operators |, & and ^, which will
  3730.              assume a bit vector operation is desired  when  both
  3731.              operands  are  strings.   This interpretation is not
  3732.              enabled unless there is at least one vec()  in  your
  3733.              program, to protect older programs.
  3734.  
  3735.              To transform a bit vector into a string or array  of
  3736.              0's and 1's, use these:
  3737.  
  3738.                   $bits = unpack("b*", $vector);
  3739.                   @bits = split(//, unpack("b*", $vector));
  3740.  
  3741.              If you know the exact length in bits, it can be used
  3742.              in place of the *.
  3743.  
  3744.      wait    Waits for a child process to terminate  and  returns
  3745.              the  pid of the deceased process, or -1 if there are
  3746.              no child processes.  The status is returned in $?.
  3747.  
  3748.      waitpid(PID,FLAGS)
  3749.              Waits for a particular child  process  to  terminate
  3750.              and  returns  the pid of the deceased process, or -1
  3751.              if there is no such child process.   The  status  is
  3752.              returned in $?.  If you say
  3753.  
  3754.                   require "sys/wait.h";
  3755.                   ...
  3756.                   waitpid(-1,&WNOHANG);
  3757.  
  3758.              then you can do a non-blocking wait for any process.
  3759.  
  3760.              Non-blocking wait is only available on machines sup-
  3761.              porting either the waitpid (2) or wait4  (2)  system
  3762.              calls.   However,  waiting for a particular pid with
  3763.              FLAGS of 0 is implemented  everywhere.   (Perl  emu-
  3764.              lates  the  system  call  by  remembering the status
  3765.              values of processes that have exited  but  have  not
  3766.              been harvested by the Perl script yet.)
  3767.  
  3768.      wantarray
  3769.              Returns true if the context of the currently execut-
  3770.              ing  subroutine  is  looking  for  an  array  value.
  3771.              Returns false  if  the  context  is  looking  for  a
  3772.              scalar.
  3773.  
  3774.                   return wantarray ? () : undef;
  3775.  
  3776.      warn(LIST)
  3777.      warn LIST
  3778.              Produces a message on STDERR just  like  "die",  but
  3779.              doesn't exit.
  3780.  
  3781.      write(FILEHANDLE)
  3782.      write(EXPR)
  3783.      write   Writes a formatted record (possibly  multi-line)  to
  3784.              the specified file, using the format associated with
  3785.              that file.  By default the format for a file is  the
  3786.              one  having the same name is the filehandle, but the
  3787.              format for the current output channel  (see  select)
  3788.              may  be  set explicitly by assigning the name of the
  3789.              format to the $~ variable.
  3790.  
  3791.              Top of form processing is handled automatically:  if
  3792.              there  is  insufficient room on the current page for
  3793.              the formatted record, the page is advanced by  writ-
  3794.              ing  a  form  feed,  a special top-of-page format is
  3795.              used to format the new page  header,  and  then  the
  3796.              record  is written.  By default the top-of-page for-
  3797.              mat is  the  name  of  the  filehandle  with  "_TOP"
  3798.              appended, but it may be dynamicallly set to the for-
  3799.              mat of your choice by assigning the name to  the  $^
  3800.              variable  while  the  filehandle  is  selected.  The
  3801.              number of lines remaining on the current page is  in
  3802.              variable  $-,  which  can be set to 0 to force a new
  3803.              page.
  3804.  
  3805.              If FILEHANDLE is unspecified,  output  goes  to  the
  3806.              current  default output channel, which starts out as
  3807.              STDOUT but may be changed by  the  select  operator.
  3808.  
  3809.              If the FILEHANDLE is an EXPR, then the expression is
  3810.              evaluated and the resulting string is used  to  look
  3811.              up the name of the FILEHANDLE at run time.  For more
  3812.              on formats, see the section on Formats later on.
  3813.  
  3814.              Note that write is NOT the opposite of read.
  3815.  
  3816. ==
  3817.      Precedence
  3818.  
  3819.      Perl operators have the  following  associativity  and  pre-
  3820.      cedence:
  3821.  
  3822.      nonassoc  print printf exec system sort reverse
  3823.                     chmod chown kill unlink utime die return
  3824.      left      ,
  3825.      right     = += -= *= etc.
  3826.      right     ?:
  3827.      nonassoc  ..
  3828.      left      ||
  3829.      left      &&
  3830.      left      | ^
  3831.      left      &
  3832.      nonassoc  == != <=> eq ne cmp
  3833.      nonassoc  < > <= >= lt gt le ge
  3834.      nonassoc  chdir exit eval reset sleep rand umask
  3835.      nonassoc  -r -w -x etc.
  3836.      left      << >>
  3837.      left      + - .
  3838.      left      * / % x
  3839.      left      =~ !~
  3840.      right     ! ~ and unary minus
  3841.      right     **
  3842.      nonassoc  ++ --
  3843.      left      '('
  3844.  
  3845.      As mentioned earlier, if any list operator (print, etc.)  or
  3846.      any  unary  operator  (chdir,  etc.)  is  followed by a left
  3847.      parenthesis as the next token on the same line, the operator
  3848.      and  arguments within parentheses are taken to be of highest
  3849.      precedence, just like a normal function call.  Examples:
  3850.  
  3851.           chdir $foo || die;       # (chdir $foo) || die
  3852.           chdir($foo) || die;      # (chdir $foo) || die
  3853.           chdir ($foo) || die;     # (chdir $foo) || die
  3854.           chdir +($foo) || die;    # (chdir $foo) || die
  3855.  
  3856.      but, because * is higher precedence than ||:
  3857.  
  3858.           chdir $foo * 20;         # chdir ($foo * 20)
  3859.           chdir($foo) * 20;        # (chdir $foo) * 20
  3860.           chdir ($foo) * 20;       # (chdir $foo) * 20
  3861.           chdir +($foo) * 20;      # chdir ($foo * 20)
  3862.  
  3863.           rand 10 * 20;            # rand (10 * 20)
  3864.           rand(10) * 20;           # (rand 10) * 20
  3865.           rand (10) * 20;          # (rand 10) * 20
  3866.           rand +(10) * 20;         # rand (10 * 20)
  3867.  
  3868.      In the absence of parentheses, the precedence of list opera-
  3869.      tors  such  as  print,  sort or chmod is either very high or
  3870.      very low depending on whether you look at the left  side  of
  3871.      operator or the right side of it.  For example, in
  3872.  
  3873.           @ary = (1, 3, sort 4, 2);
  3874.           print @ary;         # prints 1324
  3875.  
  3876.      the commas on the right of the sort are evaluated before the
  3877.      sort,  but  the  commas on the left are evaluated after.  In
  3878.      other words, list operators tend to gobble up all the  argu-
  3879.      ments that follow them, and then act like a simple term with
  3880.      regard to the preceding expression.  Note that you  have  to
  3881.      be careful with parens:
  3882.  
  3883.           # These evaluate exit before doing the print:
  3884.           print($foo, exit);  # Obviously not what you want.
  3885.           print $foo, exit;   # Nor is this.
  3886.  
  3887.           # These do the print before evaluating exit:
  3888.           (print $foo), exit; # This is what you want.
  3889.           print($foo), exit;  # Or this.
  3890.           print ($foo), exit; # Or even this.
  3891.  
  3892.      Also note that
  3893.  
  3894.           print ($foo & 255) + 1, "\n";
  3895.  
  3896.      probably doesn't do what you expect at first glance.
  3897.  
  3898.      Subroutines
  3899.  
  3900.      A subroutine may be declared as follows:
  3901.  
  3902.          sub NAME BLOCK
  3903.  
  3904.      Any arguments passed to the routine come  in  as  array  @_,
  3905.      that is ($_[0], $_[1], ...).  The array @_ is a local array,
  3906.      but its values are references to the actual  scalar  parame-
  3907.      ters.   The  return  value of the subroutine is the value of
  3908.      the last expression evaluated, and can be  either  an  array
  3909.      value  or  a  scalar value.  Alternately, a return statement
  3910.      may be used to specify the returned value and exit the  sub-
  3911.      routine.  To create local variables see the local operator.
  3912.  
  3913.      A subroutine is called using the do operator or the & opera-
  3914.      tor.
  3915.  
  3916.      Example:
  3917.  
  3918.           sub MAX {
  3919.                local($max) = pop(@_);
  3920.                foreach $foo (@_) {
  3921.                     $max = $foo if $max < $foo;
  3922.                }
  3923.                $max;
  3924.           }
  3925.  
  3926.           ...
  3927.           $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
  3928.  
  3929.      Example:
  3930.  
  3931.           # get a line, combining continuation lines
  3932.           #  that start with whitespace
  3933.           sub get_line {
  3934.                $thisline = $lookahead;
  3935.                line: while ($lookahead = <STDIN>) {
  3936.                     if ($lookahead =~ /^[ \t]/) {
  3937.                          $thisline .= $lookahead;
  3938.                     }
  3939.                     else {
  3940.                          last line;
  3941.                     }
  3942.                }
  3943.                $thisline;
  3944.           }
  3945.  
  3946.           $lookahead = <STDIN>;    # get first line
  3947.           while ($_ = do get_line()) {
  3948.                ...
  3949.           }
  3950.  
  3951.      Use array assignment to a local list to name your formal arguments:
  3952.  
  3953.           sub maybeset {
  3954.                local($key, $value) = @_;
  3955.                $foo{$key} = $value unless $foo{$key};
  3956.           }
  3957.  
  3958.      This also has the effect of turning  call-by-reference  into
  3959.      call-by-value, since the assignment copies the values.
  3960.  
  3961.      Subroutines may be called recursively.  If a  subroutine  is
  3962.      called  using the & form, the argument list is optional.  If
  3963.      omitted, no @_ array is set up for the  subroutine;  the  @_
  3964.      array  at  the  time  of  the  call is visible to subroutine
  3965.      instead.
  3966.  
  3967.           do foo(1,2,3);      # pass three arguments
  3968.           &foo(1,2,3);        # the same
  3969.  
  3970.           do foo();      # pass a null list
  3971.           &foo();             # the same
  3972.           &foo;               # pass no arguments--more efficient
  3973.  
  3974.      Passing By Reference
  3975.  
  3976.      Sometimes you don't want to pass the value of an array to  a
  3977.      subroutine but rather the name of it, so that the subroutine
  3978.      can modify the global copy of it rather than working with  a
  3979.      local  copy.   In perl you can refer to all the objects of a
  3980.      particular name by prefixing the name  with  a  star:  *foo.
  3981.      When  evaluated,  it produces a scalar value that represents
  3982.      all the objects of that name, including any filehandle, for-
  3983.      mat or subroutine.  When assigned to within a local() opera-
  3984.      tion, it causes the name mentioned to refer  to  whatever  *
  3985.      value was assigned to it.  Example:
  3986.  
  3987.           sub doubleary {
  3988.               local(*someary) = @_;
  3989.               foreach $elem (@someary) {
  3990.                $elem *= 2;
  3991.               }
  3992.           }
  3993.           do doubleary(*foo);
  3994.           do doubleary(*bar);
  3995.  
  3996.      Assignment to *name is currently recommended only  inside  a
  3997.      local().  You can actually assign to *name anywhere, but the
  3998.      previous referent of *name may be  stranded  forever.   This
  3999.      may or may not bother you.
  4000.  
  4001.      Note that scalars are already passed by  reference,  so  you
  4002.      can  modify scalar arguments without using this mechanism by
  4003.      referring explicitly to the $_[nnn] in  question.   You  can
  4004.      modify  all the elements of an array by passing all the ele-
  4005.      ments as scalars, but you have to use  the  *  mechanism  to
  4006.      push,  pop  or change the size of an array.  The * mechanism
  4007.      will probably be more efficient in any case.
  4008.  
  4009.      Since a *name value contains unprintable binary data, if  it
  4010.      is  used as an argument in a print, or as a %s argument in a
  4011.      printf or sprintf, it then has the value '*name', just so it
  4012.      prints out pretty.
  4013.  
  4014.      Even if you don't want to modify an array, this mechanism is
  4015.      useful  for  passing multiple arrays in a single LIST, since
  4016.      normally the LIST mechanism will merge all the array  values
  4017.      so that you can't extract out the individual arrays.
  4018.  
  4019.      Regular Expressions
  4020.  
  4021.      The patterns used in pattern matching  are  regular  expres-
  4022.      sions  such  as  those supplied in the Version 8 regexp rou-
  4023.      tines.  (In  fact,  the  routines  are  derived  from  Henry
  4024.      Spencer's  freely redistributable reimplementation of the V8
  4025.      routines.) In addition, \w matches an alphanumeric character
  4026.      (including  "_")  and \W a nonalphanumeric.  Word boundaries
  4027.      may be matched by \b, and  non-boundaries  by  \B.   A  whi-
  4028.      tespace character is matched by \s, non-whitespace by \S.  A
  4029.      numeric character is matched by \d, non-numeric by \D.   You
  4030.      may  use  \w, \s and \d within character classes.  Also, \n,
  4031.      \r, \f, \t  and  \NNN  have  their  normal  interpretations.
  4032.      Within character classes \b represents backspace rather than
  4033.      a word boundary.  Alternatives may be separated by  |.   The
  4034.      bracketing construct ( ... ) may also be used, in which case
  4035.      \<digit> matches the digit'th substring.   (Outside  of  the
  4036.      pattern,  always  use  $ instead of \ in front of the digit.
  4037.      The scope of $<digit> (and $`, $& and $') extends to the end
  4038.      of  the  enclosing BLOCK or eval string, or to the next pat-
  4039.      tern match with subexpressions.  The \<digit> notation some-
  4040.      times  works  outside the current pattern, but should not be
  4041.      relied upon.) You may have as many parentheses as you  wish.
  4042.      If  you have more than 9 substrings, the variables $10, $11,
  4043.      ... refer to the corresponding substring.  Within  the  pat-
  4044.      tern,  \10, \11, etc. refer back to substrings if there have
  4045.      been at least that many left parens  before  the  backrefer-
  4046.      ence.  Otherwise (for backward compatibilty) \10 is the same
  4047.      as \010, a backspace, and \11 the same as \011, a tab.   And
  4048.      so on.  (\1 through \9 are always backreferences.)
  4049.  
  4050.      $+ returns whatever the  last  bracket  match  matched.   $&
  4051.      returns  the  entire matched string.  ($0 used to return the
  4052.      same thing, but not any more.) $` returns everything  before
  4053.      the matched string.  $' returns everything after the matched
  4054.      string.  Examples:
  4055.  
  4056.           s/^([^ ]*) *([^ ]*)/$2 $1/;   # swap first two words
  4057.  
  4058.           if (/Time: (..):(..):(..)/) {
  4059.                $hours = $1;
  4060.                $minutes = $2;
  4061.                $seconds = $3;
  4062.           }
  4063.  
  4064.      By default, the ^ character is only guaranteed to  match  at
  4065.      the beginning of the string, the $ character only at the end
  4066.      (or before the newline at the end)  and  perl  does  certain
  4067.      optimizations  with  the assumption that the string contains
  4068.      only one line.  The behavior of ^ and $ on embedded newlines
  4069.      will  be  inconsistent.   You  may, however, wish to treat a
  4070.      string as a multi-line buffer, such that the  ^  will  match
  4071.      after any newline within the string, and $ will match before
  4072.      any newline.  At the cost of a little more overhead, you can
  4073.      do this by setting the variable $* to 1.  Setting it back to
  4074.      0 makes perl revert to its old behavior.
  4075.  
  4076.      To facilitate  multi-line  substitutions,  the  .  character
  4077.      never matches a newline (even when $* is 0).  In particular,
  4078.      the following leaves a newline on the $_ string:
  4079.  
  4080.           $_ = <STDIN>;
  4081.           s/.*(some_string).*/$1/;
  4082.  
  4083.      If the newline is unwanted, try one of
  4084.  
  4085.           s/.*(some_string).*\n/$1/;
  4086.           s/.*(some_string)[^\000]*/$1/;
  4087.           s/.*(some_string)(.|\n)*/$1/;
  4088.           chop; s/.*(some_string).*/$1/;
  4089.           /(some_string)/ && ($_ = $1);
  4090.  
  4091.      Any item of a regular expression may be followed with digits
  4092.      in  curly  brackets  of  the  form  {n,m}, where n gives the
  4093.      minimum number of times to match the item and  m  gives  the
  4094.      maximum.   The  form  {n} is equivalent to {n,n} and matches
  4095.      exactly n times.  The form {n,} matches  n  or  more  times.
  4096.      (If  a  curly  bracket  occurs  in  any other context, it is
  4097.      treated  as  a  regular  character.)  The  *   modifier   is
  4098.      equivalent  to {0,}, the + modifier to {1,} and the ? modif-
  4099.      ier to {0,1}.  There is no limit to the size of n or m,  but
  4100.      large numbers will chew up more memory.
  4101.  
  4102.      You will note that all backslashed  metacharacters  in  perl
  4103.      are  alphanumeric,  such  as  \b, \w, \n.  Unlike some other
  4104.      regular expression languages, there are no backslashed  sym-
  4105.      bols  that aren't alphanumeric.  So anything that looks like
  4106.      \\, \(, \), \<, \>, \{, or \} is  always  interpreted  as  a
  4107.      literal  character, not a metacharacter.  This makes it sim-
  4108.      ple to quote a string that you want to use for a pattern but
  4109.      that  you  are  afraid might contain metacharacters.  Simply
  4110.      quote all the non-alphanumeric characters:
  4111.  
  4112.           $pattern =~ s/(\W)/\\$1/g;
  4113.  
  4114.      Formats
  4115.  
  4116.      Output record formats for use with the  write  operator  may
  4117.      declared as follows:
  4118.  
  4119.          format NAME =
  4120.          FORMLIST
  4121.          .
  4122.  
  4123.      If name is omitted, format "STDOUT"  is  defined.   FORMLIST
  4124.      consists of a sequence of lines, each of which may be of one
  4125.      of three types:
  4126.  
  4127.      1.  A comment.
  4128.  
  4129.      2.  A "picture" line giving the format for one output line.
  4130.  
  4131.      3.  An argument line supplying values to plug into a picture
  4132.          line.
  4133.  
  4134.      Picture lines are printed exactly as they look,  except  for
  4135.      certain  fields  that substitute values into the line.  Each
  4136.      picture field starts with either @ or ^.  The @  field  (not
  4137.      to  be confused with the array marker @) is the normal case;
  4138.      ^ fields are used to do rudimentary  multi-line  text  block
  4139.      filling.  The length of the field is supplied by padding out
  4140.      the field with multiple <, >, or |  characters  to  specify,
  4141.      respectively,  left  justification,  right justification, or
  4142.      centering.  As an alternate form of right justification, you
  4143.      may  also use # characters (with an optional .) to specify a
  4144.      numeric field.  (Use of ^ instead of @ causes the  field  to
  4145.      be  blanked if undefined.) If any of the values supplied for
  4146.      these fields contains a newline, only the  text  up  to  the
  4147.      newline  is  printed.   The special field @* can be used for
  4148.      printing multi-line values.  It should appear by itself on a
  4149.      line.
  4150.  
  4151.      The values are specified on the following line, in the  same
  4152.      order as the picture fields.  The values should be separated
  4153.      by commas.
  4154.  
  4155.      Picture fields that begin with ^ rather than @  are  treated
  4156.      specially.   The  value  supplied  must be a scalar variable
  4157.      name which contains a text string.  Perl puts as  much  text
  4158.      as  it  can  into the field, and then chops off the front of
  4159.      the string so that the next time the variable is referenced,
  4160.      more  of  the text can be printed.  Normally you would use a
  4161.      sequence of fields in a vertical stack to print out a  block
  4162.      of text.  If you like, you can end the final field with ...,
  4163.      which will appear in the output if the text was too long  to
  4164.      appear in its entirety.  You can change which characters are
  4165.      legal to break on by changing the variable $: to a  list  of
  4166.      the desired characters.
  4167.  
  4168.      Since use of ^ fields can produce variable length records if
  4169.      the  text  to  be formatted is short, you can suppress blank
  4170.      lines by putting the tilde (~)  character  anywhere  in  the
  4171.      line.  (Normally you should put it in the front if possible,
  4172.      for visibility.) The tilde will be  translated  to  a  space
  4173.      upon  output.   If  you put a second tilde contiguous to the
  4174.      first, the line will be repeated until all the fields on the
  4175.      line  are  exhausted.  (If you use a field of the @ variety,
  4176.      the expression you supply had better not give the same value
  4177.      every time forever!)
  4178.  
  4179.      Examples:
  4180.  
  4181.      # a report on the /etc/passwd file
  4182.      format STDOUT_TOP =
  4183.                              Passwd File
  4184.      Name                Login    Office   Uid   Gid Home
  4185.      ------------------------------------------------------------------
  4186.      .
  4187.      format STDOUT =
  4188.      @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
  4189.      $name,              $login,  $office,$uid,$gid, $home
  4190.      .
  4191.  
  4192.      # a report from a bug report form
  4193.      format STDOUT_TOP =
  4194.                              Bug Reports
  4195.      @<<<<<<<<<<<<<<<<<<<<<<<     @|||         @>>>>>>>>>>>>>>>>>>>>>>>
  4196.      $system,                      $%,         $date
  4197.      ------------------------------------------------------------------
  4198.      .
  4199.      format STDOUT =
  4200.      Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4201.               $subject
  4202.      Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4203.             $index,                       $description
  4204.      Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4205.                $priority,        $date,   $description
  4206.      From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4207.            $from,                         $description
  4208.      Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4209.                   $programmer,            $description
  4210.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4211.                                           $description
  4212.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4213.                                           $description
  4214.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4215.                                           $description
  4216.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  4217.                                           $description
  4218.      ~                                    ^<<<<<<<<<<<<<<<<<<<<<<<...
  4219.                                           $description
  4220.      .
  4221.  
  4222.      It is possible to intermix prints with writes  on  the  same
  4223.      output  channel, but you'll have to handle $- (lines left on
  4224.      the page) yourself.
  4225.  
  4226.      If you are printing lots of fields that are  usually  blank,
  4227.      you   should  consider  using  the  reset  operator  between
  4228.      records.  Not only is it more efficient, but it can  prevent
  4229.      the bug of adding another field and forgetting to zero it.
  4230.  
  4231.      Interprocess Communication
  4232.  
  4233.      The IPC facilities of perl are built on the Berkeley  socket
  4234.      mechanism.   If  you don't have sockets, you can ignore this
  4235.      section.  The calls have the same names as the corresponding
  4236.      system calls, but the arguments tend to differ, for two rea-
  4237.      sons.  First, perl file handles work differently than C file
  4238.      descriptors.   Second,  perl already knows the length of its
  4239.      strings, so you don't need to pass that  information.   Here
  4240.      is a sample client (untested):
  4241.  
  4242.           ($them,$port) = @ARGV;
  4243.           $port = 2345 unless $port;
  4244.           $them = 'localhost' unless $them;
  4245.  
  4246.           $SIG{'INT'} = 'dokill';
  4247.           sub dokill { kill 9,$child if $child; }
  4248.  
  4249.           require 'sys/socket.ph';
  4250.  
  4251.           $sockaddr = 'S n a4 x8';
  4252.           chop($hostname = `hostname`);
  4253.  
  4254.           ($name, $aliases, $proto) = getprotobyname('tcp');
  4255.           ($name, $aliases, $port) = getservbyname($port, 'tcp')
  4256.                unless $port =~ /^\d+$/;
  4257.           ($name, $aliases, $type, $len, $thisaddr) =
  4258.                               gethostbyname($hostname);
  4259.           ($name, $aliases, $type, $len, $thataddr) = gethostbyname($them);
  4260.  
  4261.           $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
  4262.           $that = pack($sockaddr, &AF_INET, $port, $thataddr);
  4263.  
  4264.           socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  4265.           bind(S, $this) || die "bind: $!";
  4266.           connect(S, $that) || die "connect: $!";
  4267.  
  4268.           select(S); $| = 1; select(stdout);
  4269.  
  4270.           if ($child = fork) {
  4271.                while (<>) {
  4272.                     print S;
  4273.                }
  4274.                sleep 3;
  4275.  
  4276.                do dokill();
  4277.           }
  4278.           else {
  4279.                while (<S>) {
  4280.                     print;
  4281.                }
  4282.           }
  4283.  
  4284.      And here's a server:
  4285.  
  4286.           ($port) = @ARGV;
  4287.           $port = 2345 unless $port;
  4288.  
  4289.           require 'sys/socket.ph';
  4290.  
  4291.           $sockaddr = 'S n a4 x8';
  4292.  
  4293.           ($name, $aliases, $proto) = getprotobyname('tcp');
  4294.           ($name, $aliases, $port) = getservbyname($port, 'tcp')
  4295.                unless $port =~ /^\d+$/;
  4296.  
  4297.           $this = pack($sockaddr, &AF_INET, $port, "\0\0\0\0");
  4298.  
  4299.           select(NS); $| = 1; select(stdout);
  4300.  
  4301.           socket(S, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
  4302.           bind(S, $this) || die "bind: $!";
  4303.           listen(S, 5) || die "connect: $!";
  4304.  
  4305.           select(S); $| = 1; select(stdout);
  4306.  
  4307.           for (;;) {
  4308.                print "Listening again\n";
  4309.                ($addr = accept(NS,S)) || die $!;
  4310.                print "accept ok\n";
  4311.  
  4312.                ($af,$port,$inetaddr) = unpack($sockaddr,$addr);
  4313.                @inetaddr = unpack('C4',$inetaddr);
  4314.                print "$af $port @inetaddr\n";
  4315.  
  4316.                while (<NS>) {
  4317.                     print;
  4318.                     print NS;
  4319.                }
  4320.           }
  4321.  
  4322.      Predefined Names
  4323.  
  4324.      The following names have special meaning to perl.   I  could
  4325.      have used alphabetic symbols for some of these, but I didn't
  4326.      want to  take  the  chance  that  someone  would  say  reset
  4327.      "a-zA-Z"  and wipe them all out.  You'll just have to suffer
  4328.      along with these silly symbols.  Most of them  have  reason-
  4329.      able mnemonics, or analogues in one of the shells.
  4330.  
  4331.      $_      The default input and pattern-searching space.   The
  4332.              following pairs are equivalent:
  4333.  
  4334.                   while (<>) {...     # only equivalent in while!
  4335.                   while ($_ = <>) {...
  4336.  
  4337.                   /^Subject:/
  4338.                   $_ =~ /^Subject:/
  4339.  
  4340.                   y/a-z/A-Z/
  4341.                   $_ =~ y/a-z/A-Z/
  4342.  
  4343.                   chop
  4344.                   chop($_)
  4345.  
  4346.              (Mnemonic: underline is understood in certain opera-
  4347.              tions.)
  4348.  
  4349.      $.      The current input line number of the last filehandle
  4350.              that  was  read.   Readonly.   Remember that only an
  4351.              explicit close on the  filehandle  resets  the  line
  4352.              number.  Since <> never does an explicit close, line
  4353.              numbers increase across ARGV files (but see examples
  4354.              under  eof).  (Mnemonic: many programs use . to mean
  4355.              the current line number.)
  4356.  
  4357.      $/      The input  record  separator,  newline  by  default.
  4358.              Works  like  awk's  RS  variable, including treating
  4359.              blank lines as delimiters if set to the null string.
  4360.              You may set it to a multicharacter string to match a
  4361.              multi-character delimiter.  (Mnemonic: / is used  to
  4362.              delimit line boundaries when quoting poetry.)
  4363.  
  4364.      $,      The output field separator for the  print  operator.
  4365.              Ordinarily  the print operator simply prints out the
  4366.              comma separated fields you specify.  In order to get
  4367.              behavior  more  like  awk,  set this variable as you
  4368.              would set awk's OFS  variable  to  specify  what  is
  4369.              printed  between fields.  (Mnemonic: what is printed
  4370.              when there is a , in your print statement.)
  4371.  
  4372.      $"      This is like $, except  that  it  applies  to  array
  4373.              values  interpolated into a double-quoted string (or
  4374.              similar interpreted string).  Default  is  a  space.
  4375.              (Mnemonic: obvious, I think.)
  4376.  
  4377.      $\      The output record separator for the print  operator.
  4378.              Ordinarily  the print operator simply prints out the
  4379.              comma separated fields you specify, with no trailing
  4380.              newline  or  record  separator assumed.  In order to
  4381.              get behavior more like awk, set this variable as you
  4382.              would  set  awk's  ORS  variable  to specify what is
  4383.              printed at the end of the print.  (Mnemonic: you set
  4384.              $\  instead  of  adding  \n at the end of the print.
  4385.              Also, it's just like /, but it's what you get "back"
  4386.              from perl.)
  4387.  
  4388.      $#      The output format for printed numbers.   This  vari-
  4389.              able is a half-hearted attempt to emulate awk's OFMT
  4390.              variable.  There are times, however,  when  awk  and
  4391.              perl  have  differing  notions  of  what  is in fact
  4392.              numeric.  Also, the initial value  is  %.20g  rather
  4393.              than  %.6g,  so you need to set $# explicitly to get
  4394.              awk's value.  (Mnemonic: # is the number sign.)
  4395.  
  4396.      $%      The current page number of  the  currently  selected
  4397.              output  channel.   (Mnemonic:  %  is  page number in
  4398.              nroff.)
  4399.  
  4400.      $=      The current page length  (printable  lines)  of  the
  4401.              currently  selected  output channel.  Default is 60.
  4402.              (Mnemonic: = has horizontal lines.)
  4403.  
  4404.      $-      The  number  of  lines  left  on  the  page  of  the
  4405.              currently   selected   output  channel.   (Mnemonic:
  4406.              lines_on_page - lines_printed.)
  4407.  
  4408.      $~      The name  of  the  current  report  format  for  the
  4409.              currently  selected output channel.  Default is name
  4410.              of the filehandle.  (Mnemonic: brother to $^.)
  4411.  
  4412.      $^      The name of the current top-of-page format  for  the
  4413.              currently  selected output channel.  Default is name
  4414.              of the filehandle with "_TOP" appended.   (Mnemonic:
  4415.              points to top of page.)
  4416.  
  4417.      $|      If set to nonzero, forces a flush after every  write
  4418.              or  print  on the currently selected output channel.
  4419.              Default is 0.  Note that STDOUT  will  typically  be
  4420.              line buffered if output is to the terminal and block
  4421.              buffered otherwise.  Setting this variable is useful
  4422.              primarily when you are outputting to a pipe, such as
  4423.              when you are running a perl  script  under  rsh  and
  4424.              want   to   see   the   output  as  it's  happening.
  4425.              (Mnemonic: when you want your  pipes  to  be  piping
  4426.              hot.)
  4427.  
  4428.      $$      The process number of the perl running this  script.
  4429.              (Mnemonic: same as shells.)
  4430.  
  4431.      $?      The status returned by the last pipe close, backtick
  4432.              (``)  command or system operator.  Note that this is
  4433.              the status word returned by the wait() system  call,
  4434.              so  the exit value of the subprocess is actually ($?
  4435.              >> 8).  $? & 255 gives which  signal,  if  any,  the
  4436.              process  died  from,  and  whether  there was a core
  4437.              dump.  (Mnemonic: similar to sh and ksh.)
  4438.  
  4439.      $&      The string matched by the last  pattern  match  (not
  4440.              counting  any  matches hidden within a BLOCK or eval
  4441.              enclosed by the current BLOCK).  (Mnemonic:  like  &
  4442.              in some editors.)
  4443.  
  4444.      $`      The string preceding whatever  was  matched  by  the
  4445.              last  pattern match (not counting any matches hidden
  4446.              within a BLOCK  or  eval  enclosed  by  the  current
  4447.              BLOCK).    (Mnemonic:  `  often  precedes  a  quoted
  4448.              string.)
  4449.  
  4450.      $'      The string following whatever  was  matched  by  the
  4451.              last  pattern match (not counting any matches hidden
  4452.              within a BLOCK  or  eval  enclosed  by  the  current
  4453.              BLOCK).    (Mnemonic:   '  often  follows  a  quoted
  4454.              string.) Example:
  4455.  
  4456.                   $_ = 'abcdefghi';
  4457.                   /def/;
  4458.                   print "$`:$&:$'\n";      # prints abc:def:ghi
  4459.  
  4460.      $+      The last bracket matched by the last search pattern.
  4461.              This  is  useful if you don't know which of a set of
  4462.              alternative patterns matched.  For example:
  4463.  
  4464.                  /Version: (.*)|Revision: (.*)/ && ($rev = $+);
  4465.  
  4466.              (Mnemonic: be positive and forward looking.)
  4467.  
  4468.      $*      Set to 1 to do multiline matching within a string, 0
  4469.              to tell perl that it can assume that strings contain
  4470.              a single line, for the purpose of optimizing pattern
  4471.              matches.  Pattern matches on strings containing mul-
  4472.              tiple newlines can produce confusing results when $*
  4473.              is  0.  Default is 0.  (Mnemonic: * matches multiple
  4474.              things.) Note that this variable only influences the
  4475.              interpretation of ^ and $.  A literal newline can be
  4476.              searched for even when $* == 0.
  4477.  
  4478.      $0      Contains the name of the file  containing  the  perl
  4479.              script being executed.  Assigning to $0 modifies the
  4480.              argument  area  that   the   ps(1)   program   sees.
  4481.              (Mnemonic: same as sh and ksh.)
  4482.  
  4483.      $<digit>
  4484.              Contains the subpattern from the  corresponding  set
  4485.              of  parentheses  in  the  last  pattern matched, not
  4486.              counting patterns matched in nested blocks that have
  4487.              been exited already.  (Mnemonic: like \digit.)
  4488.  
  4489.      $[      The index of the first element in an array,  and  of
  4490.              the  first  character in a substring.  Default is 0,
  4491.              but you could set it to 1 to make perl  behave  more
  4492.              like  awk  (or  Fortran)  when subscripting and when
  4493.              evaluating  the  index()  and  substr()   functions.
  4494.              (Mnemonic: [ begins subscripts.)
  4495.  
  4496.      $]      The string printed out when you say "perl  -v".   It
  4497.              can  be  used  to  determine  at  the beginning of a
  4498.              script whether the perl  interpreter  executing  the
  4499.              script  is  in the right range of versions.  If used
  4500.              in  a  numeric  context,  returns  the   version   +
  4501.              patchlevel / 1000.  Example:
  4502.  
  4503.                   # see if getc is available
  4504.                      ($version,$patchlevel) =
  4505.                         $] =~ /(\d+\.\d+).*\nPatch level: (\d+)/;
  4506.                      print STDERR "(No filename completion available.)\n"
  4507.                         if $version * 1000 + $patchlevel < 2016;
  4508.  
  4509.              or, used numerically,
  4510.  
  4511.                   warn "No checksumming!\n" if $] < 3.019;
  4512.  
  4513.              (Mnemonic: Is this version  of  perl  in  the  right
  4514.              bracket?)
  4515.  
  4516.      $;      The subscript separator for multi-dimensional  array
  4517.              emulation.   If  you  refer  to an associative array
  4518.              element as
  4519.                   $foo{$a,$b,$c}
  4520.  
  4521.              it really means
  4522.  
  4523.                   $foo{join($;, $a, $b, $c)}
  4524.  
  4525.              But don't put
  4526.  
  4527.                   @foo{$a,$b,$c}      # a slice--note the @
  4528.  
  4529.              which means
  4530.  
  4531.                   ($foo{$a},$foo{$b},$foo{$c})
  4532.  
  4533.              Default is "\034", the same as SUBSEP in awk.   Note
  4534.              that  if  your  keys contain binary data there might
  4535.              not be any safe value for $;.  (Mnemonic: comma (the
  4536.              syntactic  subscript separator) is a semi-semicolon.
  4537.              Yeah, I know, it's pretty lame, but  $,  is  already
  4538.              taken for something more important.)
  4539.  
  4540.      $!      If used in a numeric  context,  yields  the  current
  4541.              value  of  errno, with all the usual caveats.  (This
  4542.              means that you shouldn't depend on the value  of  $!
  4543.              to  be anything in particular unless you've gotten a
  4544.              specific error return indicating a system error.) If
  4545.              used  in  a string context, yields the corresponding
  4546.              system error string.  You can assign to $! in  order
  4547.              to set errno if, for instance, you want $! to return
  4548.              the string for error n, or you want to set the  exit
  4549.              value  for  the  die operator.  (Mnemonic: What just
  4550.              went bang?)
  4551.  
  4552.      $@      The perl syntax error message  from  the  last  eval
  4553.              command.  If null, the last eval parsed and executed
  4554.              correctly (although the operations you  invoked  may
  4555.              have  failed  in  the  normal  fashion).  (Mnemonic:
  4556.              Where was the syntax error "at"?)
  4557.  
  4558.      $<      The real uid of this process.  (Mnemonic:  it's  the
  4559.              uid you came FROM, if you're running setuid.)
  4560.  
  4561.      $>      The effective uid of this process.  Example:
  4562.  
  4563.                   $< = $>;  # set real uid to the effective uid
  4564.                   ($<,$>) = ($>,$<);  # swap real and effective uid
  4565.  
  4566.              (Mnemonic: it's the uid you went TO, if you're  run-
  4567.              ning setuid.) Note: $< and $> can only be swapped on
  4568.              machines supporting setreuid().
  4569.  
  4570.      $(      The real gid of this  process.   If  you  are  on  a
  4571.              machine  that supports membership in multiple groups
  4572.              simultaneously, gives  a  space  separated  list  of
  4573.              groups  you  are  in.   The  first number is the one
  4574.              returned by getgid(), and  the  subsequent  ones  by
  4575.              getgroups(),  one  of  which  may be the same as the
  4576.              first number.  (Mnemonic: parentheses  are  used  to
  4577.              GROUP  things.   The real gid is the group you LEFT,
  4578.              if you're running setgid.)
  4579.  
  4580.      $)      The effective gid of this process.  If you are on  a
  4581.              machine  that supports membership in multiple groups
  4582.              simultaneously, gives  a  space  separated  list  of
  4583.              groups  you  are  in.   The  first number is the one
  4584.              returned by getegid(), and the  subsequent  ones  by
  4585.              getgroups(),  one  of  which  may be the same as the
  4586.              first number.  (Mnemonic: parentheses  are  used  to
  4587.              GROUP things.  The effective gid is the group that's
  4588.              RIGHT for you, if you're running setgid.)
  4589.  
  4590.              Note: $<, $>, $( and $) can only be set on  machines
  4591.              that  support the corresponding set[re][ug]id() rou-
  4592.              tine.  $( and $) can only  be  swapped  on  machines
  4593.              supporting setregid().
  4594.  
  4595.      $:      The current set of characters after which  a  string
  4596.              may  be broken to fill continuation fields (starting
  4597.              with ^) in a format.  Default is " \n-", to break on
  4598.              whitespace or hyphens.  (Mnemonic: a "colon" in poe-
  4599.              try is a part of a line.)
  4600.  
  4601.      $^D     The  current   value   of   the   debugging   flags.
  4602.              (Mnemonic: value of -D switch.)
  4603.  
  4604.      $^F     The maximum system file  descriptor,  ordinarily  2.
  4605.              System  file descriptors are passed to subprocesses,
  4606.              while higher file descriptors are  not.   During  an
  4607.              open,  system file descriptors are preserved even if
  4608.              the  open  fails.   Ordinary  file  descriptors  are
  4609.              closed before the open is attempted.
  4610.  
  4611.      $^I     The current value  of  the  inplace-edit  extension.
  4612.              Use  undef  to  disable inplace editing.  (Mnemonic:
  4613.              value of -i switch.)
  4614.  
  4615.      $^P     The internal flag that the debugger clears  so  that
  4616.              it doesn't debug itself.  You could conceivable dis-
  4617.              able debugging yourself by clearing it.
  4618.  
  4619.      $^T     The time at  which  the  script  began  running,  in
  4620.              seconds since the epoch.  The values returned by the
  4621.              -M , -A and -C filetests are based on this value.
  4622.  
  4623.      $^W     The current value of the warning switch.  (Mnemonic:
  4624.              related to the -w switch.)
  4625.  
  4626.      $^X     The name that Perl  itself  was  executed  as,  from
  4627.              argv[0].
  4628.  
  4629.      $ARGV   contains the name of the current file  when  reading
  4630.              from <>.
  4631.  
  4632.      @ARGV   The array ARGV contains the command  line  arguments
  4633.              intended  for  the  script.  Note that $#ARGV is the
  4634.              generally  number  of  arguments  minus  one,  since
  4635.              $ARGV[0]  is  the  first  argument,  NOT the command
  4636.              name.  See $0 for the command name.
  4637.  
  4638.      @INC    The array INC contains the list of  places  to  look
  4639.              for  perl  scripts  to be evaluated by the "do EXPR"
  4640.              command or the "require" command.  It initially con-
  4641.              sists  of  the  arguments  to  any  -I  command line
  4642.              switches, followed  by  the  default  perl  library,
  4643.              probably  "/usr/local/lib/perl", followed by ".", to
  4644.              represent the current directory.
  4645.  
  4646.      %INC    The associative array INC contains entries for  each
  4647.              filename   that   has  been  included  via  "do"  or
  4648.              "require".  The key is the filename  you  specified,
  4649.              and  the  value is the location of the file actually
  4650.              found.  The "require" command  uses  this  array  to
  4651.              determine  whether  a  given  file  has already been
  4652.              included.
  4653.  
  4654.      $ENV{expr}
  4655.              The associative  array  ENV  contains  your  current
  4656.              environment.   Setting  a  value  in ENV changes the
  4657.              environment for child processes.
  4658.  
  4659.      $SIG{expr}
  4660.              The associative array SIG  is  used  to  set  signal
  4661.              handlers for various signals.  Example:
  4662.  
  4663.                   sub handler {  # 1st argument is signal name
  4664.                        local($sig) = @_;
  4665.                        print "Caught a SIG$sig--shutting down\n";
  4666.                        close(LOG);
  4667.                        exit(0);
  4668.                   }
  4669.  
  4670.                   $SIG{'INT'} = 'handler';
  4671.                   $SIG{'QUIT'} = 'handler';
  4672.                   ...
  4673.                   $SIG{'INT'} = 'DEFAULT'; # restore default action
  4674.                   $SIG{'QUIT'} = 'IGNORE'; # ignore SIGQUIT
  4675.  
  4676.              The SIG array only contains values for  the  signals
  4677.              actually set within the perl script.
  4678.  
  4679.      Packages
  4680.  
  4681.      Perl provides a mechanism for alternate namespaces  to  pro-
  4682.      tect  packages  from  stomping on each others variables.  By
  4683.      default, a perl script starts  compiling  into  the  package
  4684.      known as "main".  By use of the package declaration, you can
  4685.      switch namespaces.  The scope of the package declaration  is
  4686.      from  the  declaration  itself  to  the end of the enclosing
  4687.      block (the same scope as the local()  operator).   Typically
  4688.      it  would  be the first declaration in a file to be included
  4689.      by the "require" operator.  You can switch into a package in
  4690.      more than one place; it merely influences which symbol table
  4691.      is used by the compiler for the rest of that block.  You can
  4692.      refer to variables and filehandles in other packages by pre-
  4693.      fixing the identifier with the package  name  and  a  single
  4694.      quote.   If  the package name is null, the "main" package as
  4695.      assumed.
  4696.  
  4697.      Only identifiers starting with letters  are  stored  in  the
  4698.      packages  symbol table.  All other symbols are kept in pack-
  4699.      age "main".  In addition,  the  identifiers  STDIN,  STDOUT,
  4700.      STDERR,  ARGV, ARGVOUT, ENV, INC and SIG are forced to be in
  4701.      package "main", even when used for other purposes than their
  4702.      built-in  one.  Note also that, if you have a package called
  4703.      "m", "s" or "y", the you can't use the qualified form of  an
  4704.      identifier since it will be interpreted instead as a pattern
  4705.      match, a substitution or a translation.
  4706.  
  4707.      Eval'ed strings are compiled in the  package  in  which  the
  4708.      eval  was  compiled  in.   (Assignments  to $SIG{}, however,
  4709.      assume the signal handler specified is in the main  package.
  4710.      Qualify the signal handler name if you wish to have a signal
  4711.      handler in a package.) For an example, examine perldb.pl  in
  4712.      the  perl  library.  It initially switches to the DB package
  4713.      so that the debugger doesn't interfere with variables in the
  4714.      script you are trying to debug.  At various points, however,
  4715.      it temporarily switches back to the main package to evaluate
  4716.      various expressions in the context of the main package.
  4717.  
  4718.      The symbol table for a package happens to be stored  in  the
  4719.      associative array of that name prepended with an underscore.
  4720.      The value in each entry of the associative array is what you
  4721.      are  referring to when you use the *name notation.  In fact,
  4722.      the following have the same effect (in  package  main,  any-
  4723.      way), though the first is more efficient because it does the
  4724.      symbol table lookups at compile time:
  4725.  
  4726.           local(*foo) = *bar;
  4727.           local($_main{'foo'}) = $_main{'bar'};
  4728.  
  4729.      You can use this to print out all the variables in  a  pack-
  4730.      age,  for  instance.   Here  is  dumpvar.pl  from  the  perl
  4731.      library:
  4732.  
  4733.           package dumpvar;
  4734.  
  4735.           sub main'dumpvar {
  4736.               ($package) = @_;
  4737.               local(*stab) = eval("*_$package");
  4738.               while (($key,$val) = each(%stab)) {
  4739.                   {
  4740.                       local(*entry) = $val;
  4741.                       if (defined $entry) {
  4742.                           print "\$$key = '$entry'\n";
  4743.                       }
  4744.                       if (defined @entry) {
  4745.                           print "\@$key = (\n";
  4746.                           foreach $num ($[ .. $#entry) {
  4747.                               print "  $num\t'",$entry[$num],"'\n";
  4748.                           }
  4749.                           print ")\n";
  4750.                       }
  4751.                       if ($key ne "_$package" && defined %entry) {
  4752.                           print "\%$key = (\n";
  4753.                           foreach $key (sort keys(%entry)) {
  4754.                               print "  $key\t'",$entry{$key},"'\n";
  4755.                           }
  4756.                           print ")\n";
  4757.                       }
  4758.                   }
  4759.               }
  4760.           }
  4761.  
  4762.      Note that, even though the subroutine is compiled in package
  4763.      dumpvar, the name of the subroutine is qualified so that its
  4764.      name is inserted into package "main".
  4765.  
  4766.      Style
  4767.  
  4768.      Each programmer will, of course, have his or her own prefer-
  4769.      ences  in  regards to formatting, but there are some general
  4770.      guidelines that will make your programs easier to read.
  4771.  
  4772.      1.  Just because you  CAN  do  something  a  particular  way
  4773.          doesn't  mean  that  you SHOULD do it that way.  Perl is
  4774.          designed to give you several ways  to  do  anything,  so
  4775.          consider picking the most readable one.  For instance
  4776.  
  4777.               open(FOO,$foo) || die "Can't open $foo: $!";
  4778.  
  4779.          is better than
  4780.  
  4781.               die "Can't open $foo: $!" unless open(FOO,$foo);
  4782.  
  4783.          because the second way  hides  the  main  point  of  the
  4784.          statement in a modifier.  On the other hand
  4785.  
  4786.               print "Starting analysis\n" if $verbose;
  4787.  
  4788.          is better than
  4789.  
  4790.               $verbose && print "Starting analysis\n";
  4791.  
  4792.          since the main point isn't whether the user typed -v  or
  4793.          not.
  4794.  
  4795.          Similarly, just because  an  operator  lets  you  assume
  4796.          default arguments doesn't mean that you have to make use
  4797.          of the defaults.  The defaults are there for  lazy  sys-
  4798.          tems programmers writing one-shot programs.  If you want
  4799.          your program to  be  readable,  consider  supplying  the
  4800.          argument.
  4801.  
  4802.          Along  the  same  lines,  just  because  you  can   omit
  4803.          parentheses  in  many places doesn't mean that you ought
  4804.          to:
  4805.  
  4806.               return print reverse sort num values array;
  4807.               return print(reverse(sort num (values(%array))));
  4808.  
  4809.          When in doubt, parenthesize.  At the very least it  will
  4810.          let some poor schmuck bounce on the % key in vi.
  4811.  
  4812.          Even if you aren't in doubt, consider the mental welfare
  4813.          of  the  person  who has to maintain the code after you,
  4814.          and who will probably put parens in the wrong place.
  4815.  
  4816.      2.  Don't go through silly contortions to exit a loop at the
  4817.          top  or the bottom, when perl provides the "last" opera-
  4818.          tor so you can exit in the middle.  Just  outdent  it  a
  4819.          little to make it more visible:
  4820.  
  4821.              line:
  4822.               for (;;) {
  4823.                   statements;
  4824.               last line if $foo;
  4825.                   next line if /^#/;
  4826.                   statements;
  4827.               }
  4828.  
  4829.      3.  Don't be afraid to use  loop  labels--they're  there  to
  4830.          enhance readability as well as to allow multi-level loop
  4831.          breaks.  See last example.
  4832.  
  4833.      4.  For portability, when using features  that  may  not  be
  4834.          implemented  on  every machine, test the construct in an
  4835.          eval to see if it fails.  If you know  what  version  or
  4836.          patchlevel a particular feature was implemented, you can
  4837.          test $] to see if it will be there.
  4838.  
  4839.      5.  Choose mnemonic identifiers.
  4840.  
  4841.      6.  Be consistent.
  4842.  
  4843.      Debugging
  4844.  
  4845.      If you invoke perl with a -d switch, your script will be run
  4846.      under  a  debugging  monitor.  It will halt before the first
  4847.      executable statement and ask you for a command, such as:
  4848.  
  4849.      h           Prints out a help message.
  4850.  
  4851.      T           Stack trace.
  4852.  
  4853.      s           Single step.   Executes  until  it  reaches  the
  4854.                  beginning of another statement.
  4855.  
  4856.      n           Next.  Executes over subroutine calls, until  it
  4857.                  reaches the beginning of the next statement.
  4858.  
  4859.      f           Finish.  Executes statements until it  has  fin-
  4860.                  ished the current subroutine.
  4861.  
  4862.      c           Continue.  Executes until the next breakpoint is
  4863.                  reached.
  4864.  
  4865.      c line      Continue to the specified line.  Inserts a  one-
  4866.                  time-only breakpoint at the specified line.
  4867.  
  4868.      <CR>        Repeat last n or s.
  4869.  
  4870.      l min+incr  List incr+1 lines starting at min.   If  min  is
  4871.                  omitted, starts where last listing left off.  If
  4872.                  incr is omitted, previous value of incr is used.
  4873.  
  4874.      l min-max   List lines in the indicated range.
  4875.  
  4876.      l line      List just the indicated line.
  4877.  
  4878.      l           List next window.
  4879.  
  4880.      -           List previous window.
  4881.  
  4882.      w line      List window around line.
  4883.  
  4884.      l subname   List subroutine.  If it's a long  subroutine  it
  4885.                  just lists the beginning.  Use "l" to list more.
  4886.  
  4887.      /pattern/   Regular expression search forward  for  pattern;
  4888.                  the final / is optional.
  4889.  
  4890.      ?pattern?   Regular expression search backward for  pattern;
  4891.                  the final ? is optional.
  4892.  
  4893.      L           List lines that have breakpoints or actions.
  4894.  
  4895.      S           Lists the names of all subroutines.
  4896.  
  4897.      t           Toggle trace mode on or off.
  4898.  
  4899.      b line condition
  4900.                  Set a breakpoint.  If line is  omitted,  sets  a
  4901.                  breakpoint  on the line that is about to be exe-
  4902.                  cuted.  If  a  condition  is  specified,  it  is
  4903.                  evaluated each time the statement is reached and
  4904.                  a breakpoint is taken only if the  condition  is
  4905.                  true.  Breakpoints may only be set on lines that
  4906.                  begin an executable statement.
  4907.  
  4908.      b subname condition
  4909.                  Set breakpoint at first executable line of  sub-
  4910.                  routine.
  4911.  
  4912.      d line      Delete breakpoint.  If line is omitted,  deletes
  4913.                  the  breakpoint  on the line that is about to be
  4914.                  executed.
  4915.  
  4916.      D           Delete all breakpoints.
  4917.  
  4918.      a line command
  4919.                  Set an action for line.   A  multi-line  command
  4920.                  may be entered by backslashing the newlines.
  4921.  
  4922.      A           Delete all line actions.
  4923.  
  4924.      < command   Set an action to happen  before  every  debugger
  4925.                  prompt.   A multi-line command may be entered by
  4926.                  backslashing the newlines.
  4927.  
  4928.      > command   Set an action to happen after  the  prompt  when
  4929.                  you've just given a command to return to execut-
  4930.                  ing the script.  A  multi-line  command  may  be
  4931.                  entered by backslashing the newlines.
  4932.  
  4933.      V package   List all variables in package.  Default is  main
  4934.                  package.
  4935.  
  4936.      ! number    Redo a debugging command.  If number is omitted,
  4937.                  redoes the previous command.
  4938.  
  4939.      ! -number   Redo the command that  was  that  many  commands
  4940.                  ago.
  4941.  
  4942.      H -number   Display last n commands.  Only  commands  longer
  4943.                  than  one  character  are  listed.  If number is
  4944.                  omitted, lists them all.
  4945.  
  4946.      q or ^D     Quit.
  4947.  
  4948.      command     Execute command as a perl statement.  A  missing
  4949.                  semicolon will be supplied.
  4950.  
  4951.      p expr      Same  as  "print  DB'OUT  expr".    The   DB'OUT
  4952.                  filehandle  is opened to /dev/tty, regardless of
  4953.                  where STDOUT may be redirected to.
  4954.  
  4955.      If you want to modify the debugger, copy perldb.pl from  the
  4956.      perl  library  to  your  current  directory and modify it as
  4957.      necessary.  (You'll also have to put  -I.  on  your  command
  4958.      line.) You can do some customization by setting up a .perldb
  4959.      file which contains initialization code.  For instance,  you
  4960.      could make aliases like these:
  4961.  
  4962.          $DB'alias{'len'} = 's/^len(.*)/p length($1)/';
  4963.          $DB'alias{'stop'} = 's/^stop (at|in)/b/';
  4964.          $DB'alias{'.'} =
  4965.            's/^\./p "\$DB\'sub(\$DB\'line):\t",\$DB\'line[\$DB\'line]/';
  4966.  
  4967.      Setuid Scripts
  4968.  
  4969.      Perl is designed to make it easy to write secure setuid  and
  4970.      setgid  scripts.  Unlike shells, which are based on multiple
  4971.      substitution passes on each line of the script, perl uses  a
  4972.      more   conventional  evaluation  scheme  with  fewer  hidden
  4973.      "gotchas".   Additionally,  since  the  language  has   more
  4974.      built-in  functionality,  it  has to rely less upon external
  4975.      (and possibly untrustworthy) programs to accomplish its pur-
  4976.      poses.
  4977.  
  4978.      In an unpatched 4.2 or 4.3bsd  kernel,  setuid  scripts  are
  4979.      intrinsically  insecure, but this kernel feature can be dis-
  4980.      abled.  If it is, perl can emulate  the  setuid  and  setgid
  4981.      mechanism  when  it notices the otherwise useless setuid/gid
  4982.      bits on perl scripts.  If the kernel feature isn't disabled,
  4983.      perl  will  complain  loudly  that  your  setuid  script  is
  4984.      insecure.  You'll need to either disable the  kernel  setuid
  4985.      script feature, or put a C wrapper around the script.
  4986.  
  4987.      When perl is executing a setuid  script,  it  takes  special
  4988.      precautions  to  prevent  you  from falling into any obvious
  4989.      traps.  (In some ways, a perl script is more secure than the
  4990.      corresponding   C   program.)  Any  command  line  argument,
  4991.      environment variable, or input is marked as  "tainted",  and
  4992.      may not be used, directly or indirectly, in any command that
  4993.      invokes a subshell, or in any command that  modifies  files,
  4994.      directories  or  processes.  Any variable that is set within
  4995.      an expression that has previously referenced a tainted value
  4996.      also becomes tainted (even if it is logically impossible for
  4997.      the tainted value to influence the variable).  For example:
  4998.  
  4999.           $foo = shift;            # $foo is tainted
  5000.           $bar = $foo,'bar';       # $bar is also tainted
  5001.           $xxx = <>;               # Tainted
  5002.           $path = $ENV{'PATH'};    # Tainted, but see below
  5003.           $abc = 'abc';            # Not tainted
  5004.  
  5005.           system "echo $foo";      # Insecure
  5006.           system "/bin/echo", $foo;     # Secure (doesn't use sh)
  5007.           system "echo $bar";      # Insecure
  5008.           system "echo $abc";      # Insecure until PATH set
  5009.  
  5010.           $ENV{'PATH'} = '/bin:/usr/bin';
  5011.           $ENV{'IFS'} = '' if $ENV{'IFS'} ne '';
  5012.  
  5013.           $path = $ENV{'PATH'};    # Not tainted
  5014.           system "echo $abc";      # Is secure now!
  5015.  
  5016.           open(FOO,"$foo");        # OK
  5017.           open(FOO,">$foo");       # Not OK
  5018.  
  5019.           open(FOO,"echo $foo|");  # Not OK, but...
  5020.           open(FOO,"-|") || exec 'echo', $foo;    # OK
  5021.  
  5022.           $zzz = `echo $foo`;      # Insecure, zzz tainted
  5023.  
  5024.           unlink $abc,$foo;        # Insecure
  5025.           umask $foo;              # Insecure
  5026.  
  5027.           exec "echo $foo";        # Insecure
  5028.           exec "echo", $foo;       # Secure (doesn't use sh)
  5029.           exec "sh", '-c', $foo;   # Considered secure, alas
  5030.  
  5031.      The taintedness is associated with  each  scalar  value,  so
  5032.      some elements of an array can be tainted, and others not.
  5033.  
  5034.      If you try to do something insecure, you will  get  a  fatal
  5035.      error   saying   something  like  "Insecure  dependency"  or
  5036.      "Insecure PATH".  Note that you can still write an  insecure
  5037.      system  call or exec, but only by explicitly doing something
  5038.      like the last example above.  You can also bypass the taint-
  5039.      ing mechanism by referencing subpatterns--perl presumes that
  5040.      if you reference a substring using $1,  $2,  etc,  you  knew
  5041.      what you were doing when you wrote the pattern:
  5042.  
  5043.           $ARGV[0] =~ /^-P(\w+)$/;
  5044.           $printer = $1;      # Not tainted
  5045.  
  5046.      This is fairly secure since \w+ doesn't  match  shell  meta-
  5047.      characters.   Use  of  .+ would have been insecure, but perl
  5048.      doesn't check for that, so you must  be  careful  with  your
  5049.      patterns.   This  is  the ONLY mechanism for untainting user
  5050.      supplied filenames if you want to do file operations on them
  5051.      (unless you make $> equal to $<).
  5052.  
  5053.      It's also possible to get into trouble with other operations
  5054.      that don't care whether they use tainted values.  Make judi-
  5055.      cious use of the  file  tests  in  dealing  with  any  user-
  5056.      supplied  filenames.  When possible, do opens and such after
  5057.      setting $> = $<.  Perl  doesn't  prevent  you  from  opening
  5058.      tainted  filenames for reading, so be careful what you print
  5059.      out.  The tainting mechanism is intended to  prevent  stupid
  5060.      mistakes, not to remove the need for thought.
  5061.  
  5062. ENVIRONMENT
  5063.      Perl uses PATH in executing subprocesses, and in finding the
  5064.      script  if -S is used.  HOME or LOGDIR are used if chdir has
  5065.      no argument.
  5066.  
  5067.      Apart from these, perl uses no environment variables, except
  5068.      to  make them available to the script being executed, and to
  5069.      child processes.  However, scripts running setuid  would  do
  5070.      well  to  execute  the following lines before doing anything
  5071.      else, just to keep people honest:
  5072.  
  5073.          $ENV{'PATH'} = '/bin:/usr/bin';    # or whatever you need
  5074.          $ENV{'SHELL'} = '/bin/sh' if $ENV{'SHELL'} ne '';
  5075.          $ENV{'IFS'} = '' if $ENV{'IFS'} ne '';
  5076.  
  5077. AUTHOR
  5078.      Larry Wall <lwall@netlabs.com>
  5079.      MS-DOS port by Diomidis Spinellis <dds@cc.ic.ac.uk>
  5080.      Macintosh port by Matthias Neeracher <neeri@iis.ee.ethz.ch>
  5081.  
  5082. FILES
  5083.      /tmp/perl-eXXXXXX   temporary file for -e commands.
  5084.  
  5085. SEE ALSO
  5086.      a2p  awk to perl translator
  5087.      s2p  sed to perl translator
  5088.  
  5089. DIAGNOSTICS
  5090.      Compilation errors will tell you  the  line  number  of  the
  5091.      error,  with  an  indication of the next token or token type
  5092.      that was to be examined.  (In the case of a script passed to
  5093.      perl via -e switches, each -e is counted as one line.)
  5094.  
  5095.      Setuid scripts have additional constraints that can  produce
  5096.      error  messages such as "Insecure dependency".  See the sec-
  5097.      tion on setuid scripts.
  5098.  
  5099. TRAPS
  5100.      Accustomed awk users should take special note of the follow-
  5101.      ing:
  5102.  
  5103.      *   Semicolons are required after all simple  statements  in
  5104.          perl.  Newline is not a statement delimiter.
  5105.  
  5106.      *   Curly brackets are required on ifs and whiles.
  5107.  
  5108.      *   Variables begin with $ or @ in perl.
  5109.  
  5110.      *   Arrays index from 0 unless you set $[.  Likewise  string
  5111.          positions in substr() and index().
  5112.  
  5113.      *   You have to decide whether your  array  has  numeric  or
  5114.          string indices.
  5115.  
  5116.      *   Associative array values do not  spring  into  existence
  5117.          upon mere reference.
  5118.  
  5119.      *   You have to decide whether you want  to  use  string  or
  5120.          numeric comparisons.
  5121.  
  5122.      *   Reading an input line does not split it  for  you.   You
  5123.          get  to  split  it  yourself to an array.  And the split
  5124.          operator has different arguments.
  5125.  
  5126.      *   The current input line is normally in $_,  not  $0.   It
  5127.          generally  does  not  have the newline stripped.  ($0 is
  5128.          the name of the program executed.)
  5129.  
  5130.      *   $<digit> does not refer to  fields--it  refers  to  sub-
  5131.          strings matched by the last match pattern.
  5132.  
  5133.      *   The print  statement  does  not  add  field  and  record
  5134.          separators unless you set $, and $\.
  5135.  
  5136.      *   You must open your files before you print to them.
  5137.  
  5138.      *   The range operator  is  "..",  not  comma.   (The  comma
  5139.          operator works as in C.)
  5140.  
  5141.      *   The match operator is "=~", not "~".  ("~" is the  one's
  5142.          complement operator, as in C.)
  5143.  
  5144.      *   The exponentiation operator is "**", not "^".   ("^"  is
  5145.          the XOR operator, as in C.)
  5146.  
  5147.      *   The concatenation operator is ".", not the null  string.
  5148.          (Using  the  null  string  would  render  "/pat/  /pat/"
  5149.          unparsable, since the third slash would  be  interpreted
  5150.          as  a division operator--the tokener is in fact slightly
  5151.          context sensitive for operators like /, ?, and  <.   And
  5152.          in fact, . itself can be the beginning of a number.)
  5153.  
  5154.      *   Next, exit and continue work differently.
  5155.  
  5156.      *   The following variables work differently
  5157.  
  5158.                 Awk               Perl
  5159.                 ARGC              $#ARGV
  5160.                 ARGV[0]           $0
  5161.                 FILENAME          $ARGV
  5162.                 FNR               $. - something
  5163.                 FS                (whatever you like)
  5164.                 NF                $#Fld, or some such
  5165.                 NR                $.
  5166.                 OFMT              $#
  5167.                 OFS               $,
  5168.                 ORS               $\
  5169.                 RLENGTH           length($&)
  5170.                 RS                $/
  5171.                 RSTART            length($`)
  5172.                 SUBSEP            $;
  5173.  
  5174.      *   When in doubt, run the awk construct through a2p and see
  5175.          what it gives you.
  5176.  
  5177.      Cerebral C programmers should take note of the following:
  5178.  
  5179.      *   Curly brackets are required on ifs and whiles.
  5180.  
  5181.      *   You should use "elsif" rather than "else if"
  5182.  
  5183.      *   Break and continue become last and next, respectively.
  5184.  
  5185.      *   There's no switch statement.
  5186.  
  5187.      *   Variables begin with $ or @ in perl.
  5188.  
  5189.      *   Printf does not implement *.
  5190.  
  5191.      *   Comments begin with #, not /*.
  5192.  
  5193.      *   You can't take the address of anything.
  5194.  
  5195.      *   ARGV must be capitalized.
  5196.  
  5197.      *   The "system" calls link,  unlink,  rename,  etc.  return
  5198.          nonzero for success, not 0.
  5199.  
  5200.      *   Signal handlers deal with signal names, not numbers.
  5201.  
  5202.      Seasoned sed programmers should take note of the following:
  5203.  
  5204.      *   Backreferences in substitutions use $ rather than \.
  5205.  
  5206.      *   The pattern matching metacharacters (, ), and |  do  not
  5207.          have backslashes in front.
  5208.  
  5209.      *   The range operator is .. rather than comma.
  5210.  
  5211.      Sharp shell programmers should take note of the following:
  5212.  
  5213.      *   The  backtick  operator  does  variable   interpretation
  5214.          without  regard  to the presence of single quotes in the
  5215.          command.
  5216.  
  5217.      *   The backtick operator does no translation of the  return
  5218.          value, unlike csh.
  5219.  
  5220.      *   Shells (especially csh) do several levels  of  substitu-
  5221.          tion  on each command line.  Perl does substitution only
  5222.          in certain constructs such as double quotes,  backticks,
  5223.          angle brackets and search patterns.
  5224.  
  5225.      *   Shells interpret scripts a little bit at a  time.   Perl
  5226.          compiles the whole program before executing it.
  5227.  
  5228.      *   The arguments are available via @ARGV, not $1, $2, etc.
  5229.  
  5230.      *   The environment is not automatically made  available  as
  5231.          variables.
  5232.  
  5233. ERRATA AND ADDENDA
  5234.      The Perl book, Programming Perl , has  the  following  omis-
  5235.      sions and goofs.
  5236.  
  5237.      On page 5, the examples which read
  5238.  
  5239.           eval "/usr/bin/perl
  5240.  
  5241.      should read
  5242.  
  5243.           eval "exec /usr/bin/perl
  5244.  
  5245.      On page 195, the equivalent to the System V sum program only
  5246.      works for very small files.  To do larger files, use
  5247.  
  5248.           undef $/;
  5249.  
  5250.           $checksum = unpack("%32C*",<>) % 32767;
  5251.  
  5252.      The  descriptions  of  alarm  and  sleep  refer  to   signal
  5253.      SIGALARM.  These should refer to SIGALRM.
  5254.  
  5255.      The -0 switch to set the initial value of $/  was  added  to
  5256.      Perl after the book went to press.
  5257.  
  5258.      The -l switch now does automatic line ending processing.
  5259.  
  5260.      The qx// construct is now a synonym for backticks.
  5261.  
  5262.      $0 may now be assigned to set the argument displayed  by  ps
  5263.      (1).
  5264.  
  5265.      The new @###.## format was  omitted  accidentally  from  the
  5266.      description on formats.
  5267.  
  5268.      It wasn't known at press time that  s///ee  caused  multiple
  5269.      evaluations  of  the  replacement expression.  This is to be
  5270.      construed as a feature.
  5271.  
  5272.      (LIST) x $count now does array replication.
  5273.  
  5274.      There is now no limit on the number of parentheses in a reg-
  5275.      ular expression.
  5276.  
  5277.      In double-quote context, more escapes are supported: \e, \a,
  5278.      \x1b,  \c[,  \l,  \L,  \u,  \U, \E.  The latter five control
  5279.      up/lower case translation.
  5280.  
  5281.      The $/ variable may now be set to a  multi-character  delim-
  5282.      iter.
  5283.  
  5284.      There is now a g modifier on ordinary pattern matching  that
  5285.      causes  it  to  iterate  through  a  string finding multiple
  5286.      matches.
  5287.  
  5288.      All of the $^X variables are new except for $^T.
  5289.  
  5290.      The  default  top-of-form  format  for  FILEHANDLE  is   now
  5291.      FILEHANDLE_TOP rather than top.
  5292.  
  5293.      The eval {} and sort {} constructs  were  added  in  version
  5294.      4.018.
  5295.  
  5296.      The v and V (little-endian) template options  for  pack  and
  5297.      unpack were added in 4.019.
  5298.  
  5299. BUGS
  5300.      Perl is at the mercy of your machine's definitions of  vari-
  5301.      ous operations such as type casting, atof() and sprintf().
  5302.  
  5303.      If your stdio requires an seek  or  eof  between  reads  and
  5304.      writes  on a particular stream, so does perl.  (This doesn't
  5305.      apply to sysread() and syswrite().)
  5306.  
  5307.      While none of the built-in data  types  have  any  arbitrary
  5308.      size  limits (apart from memory size), there are still a few
  5309.      arbitrary limits: a given identifier may not be longer  than
  5310.      255  characters, and no component of your PATH may be longer
  5311.      than 255 if you use -S.
  5312.  
  5313.      Perl actually stands  for  Pathologically  Eclectic  Rubbish
  5314.      Lister, but don't tell anyone I said that.
  5315.  
  5316.